完成处理程序和返回值

时间:2013-04-27 17:04:08

标签: ios objective-c asynchronous return objective-c-blocks

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

// 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完成之前返回值。我无法在请求的响应处理程序内返回当前客户端。那么我的选择是什么?

1 个答案:

答案 0 :(得分:19)

您需要更改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将立即返回,而网络请求将在另一个线程上调度。不要忘记,如果您想使用响应处理程序更新UI,则需要使用处理程序run on the main thread