完成处理程序和返回值

我想调用一个方法,它将从其完成处理程序返回一个值。 该方法asynchronous执行,我不想在方法的所有主体执行之前返回一个值。 下面是一些错误的代码来说明我想要实现的:

// This is the way I want to call the method NSDictionary *account = [_accountModel getCurrentClient]; // This is the faulty method that I want to fix - (NSDictionary *)getCurrentClient { __block NSDictionary *currentClient = nil; NXOAuth2Account *currentAccount = [[[NXOAuth2AccountStore sharedStore] accounts] lastObject]; [NXOAuth2Request performMethod:@"GET" onResource:[NSURL URLWithString:[NSString stringWithFormat:@"%@/clients/%@", kCatapultHost, currentAccount.userData[@"account_name"]]] usingParameters:nil withAccount:currentAccount sendProgressHandler:nil responseHandler:^ (NSURLResponse *response, NSData *responseData, NSError *error) { NSError *jsonError; currentClient = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&jsonError]; }]; return currentClient; } 

我不希望getCurrentClient方法返回一个值,直到NXOAuth2Request完成。 我不能返回请求的响应处理程序中的当前客户端。 那么我有什么select?

您需要更改getCurrentClient以接收完成块,而不是返回值。

例如:

 -(void)getCurrentClientWithCompletionHandler:(void (^)(NSDictionary* currentClient))handler { NXOAuth2Account *currentAccount = [[[NXOAuth2AccountStore sharedStore] accounts] lastObject]; [NXOAuth2Request performMethod:@"GET" onResource:[NSURL URLWithString:[NSString stringWithFormat:@"%@/clients/%@", kCatapultHost, currentAccount.userData[@"account_name"]]] usingParameters:nil withAccount:currentAccount sendProgressHandler:nil responseHandler:^ (NSURLResponse *response, NSData *responseData, NSError *error) { NSError *jsonError; NSDictionary* deserializedDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&jsonError]; handler(deserializedDict); }]; } 

请记住, getCurrentClient将立即返回,而networking请求在另一个线程上分派,这一点很重要。 不要忘记,如果你想用你的响应处理程序更新UI,你需要让你的处理程序在主线程上运行 。