I want to return from outer function from inside async inner function.
In swift, I would have used completion handler for this purpose which would escape from function. But in Objective-C, completion handler won't actually return from function:
My function looks like this:
-(void)chosenFrom:(NSDictionary<NSString *,id> *)info{
[self asyncCode:info withCompletion:^(NSData *imageData) {
if(imageData) {
// I want to return from chosenFrom function ***inside here.***
}
}];
// This is to illustrate completion handler don't escape
[self checkCompletionEscaping:^(NSString * lad) {
NSLog(@"Check me %@", lad);// It would print all 3 lines below.
}];
}
-(void) checkCompletionEscaping:(void(^)(NSString * lad)) completion {
completion(@"Hello"); // completion handler should've escaped from func.
completion(@"Shivam");
completion(@"How are you");
}
If I were to use Swift, I could have easily returned from outer function from inside inner function using completion handler:
private func getHistoryKeys(searchterm: String, completion: @escaping () -> ()) {
let url = PubmedAPI.createEsearchURL(searchString: searchterm)
let task = session.dataTask(with: url) { (data, response, error) in
if let error = error {
completion() // This would work as return
} else {
completion() // Same as return
}
}
task.resume()
}
PS: escaping means returning from function just like return statement.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…