処理に少し時間がかかるコードがあるため、メインキューで実行しないでください。ただし、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
}
}