Normally in iOS it is always good to go for an asynchronous API. Because we should not make the UI freeze due to synchronous API calls.
Let's first create a synchronous method which take some time to return.
This is the asynchronous block based implementation.
- (NSString*)methodSync {
for (int i = 0; i < 20; i++) {
[NSThread sleepForTimeInterval:1.0];
}
}
If we can turn this into a block based async method, it would be nice. So this is what you should do.- Call the synchronous method in a background thread
- when the execution of the method finishes, we can get the result
- The result can be processed by a block created by the user
This is the asynchronous block based implementation.
-(void)methodAsync:(void(^)(NSString *rslt))completionHnadler {
NSString __block *res;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
res = [self methodSync];
});
dispatch_group_notify(group, queue, ^{
completionHnadler(res);
});
}
Here I am using dispatch groups to wait till the synchronous method finishes.
This is how to call the new method
[self methodAsync:^(NSString *rslt) {
NSLog(rslt);
}];
For any query, feel free to contact me via my linkedin profile.
No comments:
Post a Comment