8

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

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

4

1 回答 1

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,您需要让处理程序在主线程上运行

于 2013-04-27T17:07:48.347 回答