【发布时间】:2012-12-05 06:25:36
【问题描述】:
我有一些代码需要一些时间来处理,因此它不应该在主队列上运行。但是我不确定如何正确“构造” GCD 代码段。即每次应用程序处于活动状态时,我都会进行同步操作:
AppDelegate.m
- (void)applicationDidBecomeActive:(UIApplication *)application {
AddressBookHelper *abHelper = [AddressBookHelper sharedInstance]; // singleton helper class of NSObject
[abHelper sync];
}
AddressBookHelper 中的同步代码如下所示:
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];
});
}
AddressBookHelper.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
}
}
【问题讨论】:
-
我觉得你很好,对我来说似乎是正确的
标签: objective-c cocoa grand-central-dispatch