块运行后__block变量返回nil

时间:2017-03-05 07:47:35

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

我创建了一个我用__block标识符作为前缀的字符串,这样我就可以访问我的块之外的那个变量了。但是,一旦我尝试运行该应用程序,该变量就会返回' nil':

-(void)downloadParcelData {
    __block NSString *test;

    MKMapRect mRect = self.mapView.visibleMapRect;
    NSArray *array = [NSArray array];
    array = [self getBoundingBox:mRect];

    NSString *polygonString = [self convertCoordinates:array];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = nil;

    NSDictionary *parameters = @{@"client" : @"xxxxxxxxxx",
                             @"spatial_intersect" : [NSString    stringWithFormat:@"POLYGON((%@))", [polygonString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]]]};

    [manager GET:@"someURL" parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        test = responseObject[@"txn_id"];
     } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"Error: %@", error);
     }];

    [self fetchParcelData:test];

}

关于为什么会发生这种情况的任何想法?提前谢谢。

1 个答案:

答案 0 :(得分:3)

[manager GET:parameters:progress:success:failure]似乎是一种异步方法。那条线不会阻挡;执行立即继续[self fetchParcelData:]。成功块是您应该放置要处理GET请求响应的代码的地方。