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

时间:2012-12-28 04:17:43

标签: iphone objective-c ios afnetworking

The following code is taken from this tutorial

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

1 个答案:

答案 0 :(得分: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");