AFJSONRequestOperation数组填充,但不能NSLog成功块外的内容

以下代码摘自本教程

我之前使用过这个片段,但之前从未注意过这个问题。 数组内容的NSLog将在委托方法中打印,但不在成功块外部的viewDidLoad中打印。 我需要一种方法将JSON数据保存到一个数组中,以便在代码中的其他地方使用。 我还应该补充说,我没有使用UITableView来显示我的数据。 我错过了什么,或者我该如何做到这一点?

这不会打印JSON内容,因为它会填充数组:

#import "AFNetworking.h" ... - (void)viewDidLoad { ... self.movies = [[NSArray alloc] init]; NSURL *url = [[NSURL alloc] initWithString:@"http://itunes.apple.com/search?term=harry&country=us&entity=movie"]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { self.movies = [JSON objectForKey:@"results"]; [self.activityIndicatorView stopAnimating]; [self.tableView setHidden:NO]; [self.tableView reloadData]; } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo); }]; [operation start]; NSLog(@"self.movies %@",self.movies); // does not print ... } 

这不会打印JSON内容:我只使用numberOfRowsInSection作为NSLog语句的单独位置。

 - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (self.movies && self.movies.count) { NSLog(@"self.movies %@",self.movies); // prints ... } 

您正在开始asynchronous操作,然后立即尝试打印出内容。 将您的第一个NSLog语句移入成功块。

 AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { //the following lines of code execute after the response arrives self.movies = [JSON objectForKey:@"results"]; NSLog(@"self.movies %@",self.movies); } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) { NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo); }]; [operation start]; //this line of code executes directly after the request is made, //and the response hasn't arrived yet NSLog(@"I probably don't have the response yet");