AFJSONRequestOperation阵列填充但能够成功块之外不NSLog的内容(AFJSON

2019-07-17 15:32发布

下面的代码是从本教程所

我以前用过这个片段,但之前,我从来没有注意到这个问题。 在委托方法数组内容打印的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
...
}

Answer 1:

您正在拉开的非同步操作,然后立即尝试内容打印出来。 将您的第一个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");


文章来源: AFJSONRequestOperation array populates but cannot NSLog contents outside of success block