If you are trying to synchronize several asynchronous operations (over the network or otherwise), I cannot recommend enough using promises. For a general introduction to promises, a recent Los Techies blog entry is pretty good:
http://lostechies.com/derickbailey/2012/07/19/want-to-build-win8winjs-apps-you-need-to-understand-promises/
However, there is a good library called KSPromise , which I used quite a lot in iOS: https://github.com/kseebaldt/deferred
Using promises, you can execute a fetch request after completing one or more asynchronous calls. For example, the promise of union will be resolved only after all of its dependent promises have also been resolved! I think you will find that with promises your code becomes more organized and easier to read, especially if you are doing something complicated.
However, here's a pretty far-fetched example showing a possible way to write code using promises (written against the SDK for iOS 3.1):
- (IBAction)checkFacebookInfo:(FBSession *)session { KSDeferred *dfd = [KSDeferred defer]; FBRequest *meRequest = [[FBRequest alloc] initWithSession:session graphPath:@"/me"]; [meRequest startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) { if (error) { [dfd.promise rejectWithError:error]; } else { [dfd.promise resolveWithValue:user]; } }]; [dfd.promise whenResolved:^(KSPromise *p) { NSDictionary *userInfo = p.value; NSManagedObjectContext *managedObjectContext = [[SingletonCoreData sharedManager] managedObjectContext]; NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"User"]; NSError *error; NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Last: Be very careful when using Core Data with streams and dispatch_async . You can run all kinds of hard-to-debug concurrency issues.
source share