Reputation: 652
In my app i have two methods, storeData and gotoNextView. I want the gotoNextPage to be executed after storeData method has completed execution. In storeData i am saving the token obtained after sucessful login using Egocache, in gotoNextPage i have code which is used to load a new view controller, in the next viewcontroller i have to use the token for fetching the other details. But the problem the method gotoNextView is being executed before the storeData so i am gettin null token in the next view.
I have tried using the following :
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
[self storeData];
});
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
[self gotoNextPage];
the above code is serving the purpose but when i am using the above code, the NSUrlConnections in the next view are not loading.
[self storeData];
[self performSelector:@selector(gotoNextPage) withObject:nil afterDelay:1.0f];
this code is working and the NSUrlConnections in next view also working, but is there a better way to achieve this purpose
Upvotes: 2
Views: 2986
Reputation: 11806
You could pass a completion block to the storeData method. That way storeData can let you know when it's finished doing what it needs to do, instead of you trying to guess.
- (void)storeDataWithCompletion:(void (^)(void))completion
{
// Store Data Processing...
if (completion) {
completion();
}
}
// Calling storeDataWithCompletion...
[self storeDataWithCompletion:^{
dispatch_async(dispatch_get_main_queue(), ^{
[self gotoNextPage];
});
}];
The dispatch_async to the main queue is not required. I added that since gotoNextPage is UI related and it's not clear what thread storeDataWithCompletion: would call the completion block from.
Here's a link to Apple's documentation on blocks
Hope this helps.
Upvotes: 4