我有一些代码需要一些时间来处理,因此它不应该在主队列上运行。但是我不确定如何正确“构造” GCD 代码段。即每次应用程序激活时,我都在进行同步操作:
AppDelegate.m
- (void)applicationDidBecomeActive:(UIApplication *)application {
AddressBookHelper *abHelper = [AddressBookHelper sharedInstance]; // singleton helper class of NSObject
[abHelper sync];
}
AddressBookHelper 中的同步代码如下所示:
地址簿助手.m
- (void)sync {
NSArray *people = // Fetching some people from Core Data
NSMutableArray *syncConflicts;
// Start doing some business logic, iterating over data and so on
for (id object in people) {
// Process some data
[syncConflicts addObject:object];
}
self.syncConflicts = syncConflicts;
// I have separated this method to keep the code cleaner and to separate the logic of the methods
[self processSyncConflicts];
}
- (void)processSyncConflicts {
if ([self.syncConflicts count] > 0) {
// Alert the user about the sync conflict by showing a UIAlertView to take action
UIAlertView *alert;
[alert show];
} else {
// Syncing is complete
}
}
那么有了这个代码结构,我该如何正确地使用 GCD 把这个代码放在后台线程上呢?
就这么简单吗?
AppDelegate.m
- (void)applicationDidBecomeActive:(UIApplication *)application {
AddressBookHelper *abHelper = [AddressBookHelper sharedInstance]; // singleton helper class of NSObject
dispatch_queue_t queue = dispatch_queue_create("addressbookSyncQueue", 0);
dispatch_async(queue, ^{
[abHelper sync];
});
}
地址簿助手.m
- (void)processSyncConflicts {
if ([self.syncConflicts count] > 0) {
// Alert the user about the sync conflict by showing a UIAlertView to take action
UIAlertView *alert;
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^{
[alert show];
});
} else {
// Syncing is complete
}
}