1

以下代码取自本教程

我以前使用过这个片段,但我以前从未注意到这个问题。数组内容的 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
...
}
4

1 回答 1

3

您正在启动异步操作,然后立即尝试打印出内容。将您的第一个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");
于 2012-12-28T04:46:30.643 回答