I requested and tried to understand how completion handlers work. I used a lot and I read a lot of textbooks. I will post the one that I use here, but I want to be able to create my own without using another user's code as a link.
I understand this completion handler where this caller method is:
-(void)viewDidLoad{ [newSimpleCounter countToTenThousandAndReturnCompletionBLock:^(BOOL completed){ if(completed){ NSLog(@"Ten Thousands Counts Finished"); } }]; }
and then in the called method:
-(void)countToTenThousandAndReturnCompletionBLock:(void (^)(BOOL))completed{ int x = 1; while (x < 10001) { NSLog(@"%i", x); x++; } completed(YES); }
Then I tried this option based on many SO posts:
- (void)viewDidLoad{ [self.spinner startAnimating]; [SantiappsHelper fetchUsersWithCompletionHandler:^(NSArray *users) { self.usersArray = users; [self.tableView reloadData]; }]; }
which will reload the table view by the data recipients after calling this method:
typedef void (^Handler)(NSArray *users); +(void)fetchUsersWithCompletionHandler:(Handler)handler { NSURL *url = [NSURL URLWithString:@"http://www.somewebservice.com"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10]; [request setHTTPMethod: @"GET"]; **
I see this in the counter example that the called method (with the passed block) will never exit the loop until it is executed. So the part of the “completion” actually depends on the code inside the called method, and not on the block that it passed?
In this case, the “completion” part depends on the fact that the NSURLRequest call is synchronous. What if it was asynchronous? How can I refrain from calling a block until my data is filled with NSURLResponse?
source share