我有這樣的方法試圖瞭解異步調用
- (NSString*) createUserWithName:(NSString*)TheName
{
NSURL *URL =someUrlthatIncludesTheName
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"GET"];
NSURLSession *session = [NSURLSession sharedSession];
NSURL *URL = [NSURL URLWithString:url];
NSURLSessionTask *task = [session dataTaskWithURL:URL completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (response) {
NSError* error = nil;
NSArray *output = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
myID = [[output objectAtIndex:0] objectForKey:@"UserID"];
}
}];
[task resume];
return myID;
}
而另一種方法
-(void)doSomethingWith: (NSString*) anID
某處在我的代碼,我隨後調用這些方法,像這樣:
[self createUserWithName:@"John"];
[self doSomethingWith:myID];
但是,由於NSURLSession in createUserWithName:
是異步的,doSomethingWith:
與myID =(null)一起被觸發。
解決此問題的最佳方法是什麼,而不必回退到廢棄的同步NSURLConnection?提前
這是因爲''而所述方法[自doSomethingWith:本身份識別碼] createUserWithName'尚未完成調用它執行'。你可以調用'[self doSomethingWith:myID];'進入'createUserWithName'方法或者使用CompletionBlock – vroldan