AFNetworking阻止变量更新问题

时间:2013-11-26 20:59:48

标签: iphone objective-c json afnetworking

我正在使用AFNetworking从服务器接收JSON,我使用这个JSON来确定Objective-C函数的返回值。无论JSON是什么,d的值都不会从初始化时改变(作为假值)。为什么会这样?我的代码如下:

-(BOOL)someFunction{
    __block BOOL d;
    d = FALSE;
    //the value of d is no longer changed
    operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
            if(![[jsonObject allKeys] containsObject:@"someString"]){
                d = TRUE;
            }
            else {
                d = FALSE;
            }
        }
        failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"Alert"
                                                            message: @"Could not connect to server!"
                                                           delegate: nil
                                                  cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
            [alert show];
            d = FALSE;
        }];
    [operation start];
    return d;
}

2 个答案:

答案 0 :(得分:2)

您应该使用async函数和一个返回成功BOOL的完成块。

- (void)myBeautifulFunction
{
    [self someFunctionWithCompletion:^(BOOL success) {
        if (!success) {
            [self showAlert];
        }
    }];
}

- (void)someFunctionWithCompletion:(void (^)(BOOL success))completion 
{
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        success:^(NSURLRequest *req, NSHTTPURLResponse *response, id jsonObject) {
            if (![[jsonObject allKeys] containsObject:@"someString"]){
                if (completion) {
                    completion(YES);
                }
            } else {
                if (completion) {
                    completion(NO);
                }
            }
        } failure:^(NSURLRequest *req, NSHTTPURLResponse *response, NSError *error, id jsonObject) {
            if (completion) {
                completion(NO);
            }
        }];
    [operation start];
}

答案 1 :(得分:0)

操作将以异步方式执行,但同步返回d的值。您应该从操作完成块

中触发需要d值的任何内容