以下代码摘自本教程 http://mobile.tutsplus.com/tutorials/iphone/ios-sdk_afnetworking/
我以前用过这个片段,但之前从未注意到这个问题。数组内容的 NSLog 在委托方法中打印,但不在 success 块之外的 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
...
}