2

我在块内将值设置为 NSString 时遇到问题。

__block NSString *cityID = [[NSString alloc] init];
AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id json) {
                                         cityID = [NSString stringWithFormat:@"%@",[[json valueForKeyPath:@"location"] valueForKey:@"id"]];
                                         NSLog(@"city id for 621352674 = %@",cityID);
                                     } failure:nil]; 
[operation start];
NSLog(@"city id for 621352674 = %@",cityID);

第一个 NSLog 显示了 cityID 的正确值。但第二个什么也没显示。如何解决这个问题?

4

2 回答 2

4

第二个NSLog()不是等待块完成。这实际上是操作的重点:它在后台运行,因此当通过网络获取数据时,主线程和应用程序的 UI 不会被锁定。当您在开始操作后立即进行该调用时,该字符串的值没有改变。如果您更改 s 中字符串的文字部分NSLog()

                             NSLog(@"In Block: city id for 621352674 = %@",cityID);
                                 } failure:nil]; 
[operation start];
NSLog(@"After operation start: city id for 621352674 = %@",cityID);

你可能会更清楚发生了什么。

于 2012-05-07T19:58:57.880 回答
3

实际上,第二个 NSLog 先出现,第一个 NSLog 再出现......所以你收到的反馈是正确的。你没问题,你的字符串值已经设置好了,当操作完成时......

于 2012-05-07T19:59:06.503 回答