這是給調用者提供的代碼通過方法(塊體)上運行。實現者需要調用該代碼。
要開始一個簡單的例子,比如說來電者只是想讓你形成與urlString數組和回調,那麼你可以這樣做:
- (void)downloadedDataURLString:(NSString *)urlString
completionHandler:(void (^)(NSArray *, NSError *))completionHandler {
NSArray *callBackWithThis = @[urlString, @"Look ma, no hands"];
completionHandler(callBackWithThis, nil);
}
主叫方這樣做:
- (void)someMethodInTheSameClass {
// make an array
[self downloadedDataURLString:@"put me in an array"
completionHandler:^(NSArray *array, NSError *error) {
NSLog(@"called back with %@", array);
}];
}
來電者將記錄兩個項目陣列@「把我的數組」,並@「媽媽快看,沒有動手。」在一個更現實的例子中,假設有人要求你在完成下載任務時給他們回電話:
- (void)downloadedDataURLString:(NSString *)urlString
completionHandler:(void (^)(NSArray *, NSError *))completionHandler {
// imagine your caller wants you to do a GET from a web api
// stripped down, that would look like this
// build a request
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// run it asynch
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error) {
// imagine that the api answers a JSON array. parse it
NSError *parseError;
id parse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
// here's the part you care about: the completionHandler can be called like a function. the code the caller supplies will be run
if (!parseError) {
completionHandler(parse, nil);
} else {
NSLog(@"json parse error, error is %@", parseError);
completionHandler(nil, parseError);
}
} else {
NSLog(@"error making request %@", error);
completionHandler(nil, error);
}
}];
// remember, this launches the request and returns right away
// you are calling the block later, after the request has finished
}
你不能確定從塊簽名本身,當然沒有給出參數名稱。你必須閱讀文檔或一些示例代碼。我們無法幫助。 – trojanfoe
我用更多的代碼更新了它。 – jimbob
嗯,我們可以猜測它做了什麼,但它只是一個猜測。就像任何方法一樣,例如,我向您提供了它,它做了什麼以及如何正確使用它是通過文檔和/或示例進行交流的。有多種方法可以實現同樣的目標。你需要參考代碼的作者,或者至少發佈一個鏈接供我們關注。 – trojanfoe