__block variable returning nil after block runs [d

2020-05-07 13:53发布

I have a created a string that I have prefixed with the __block identifier so that I am able to access that variable outside of my block. However once I attempt to run the application the variable returns '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];

}

Any ideas on why this may be happening? Thanks in advance.

1条回答
贪生不怕死
2楼-- · 2020-05-07 14:31

[manager GET:parameters:progress:success:failure] appears to be an async method. That line does not block; execution immediately continues to [self fetchParcelData:]. The success block is where you should put code you want to handle the response to the GET request.

查看更多
登录 后发表回答