AFJSONRequestOperation array populates but cannot

2020-03-30 15:56发布

问题:

The following code is taken from this tutorial

I've used this snippet before but I never noticed this issue before. NSLog of the array contents prints in a delegate method but not in the viewDidLoad outside of the success block. I require a way to save the JSON data into an array for use elsewhere in the code. I should also add that I'm not using UITableView to display my data. What am I missing or how can I accomplish this?

This does not print the JSON content thought it does populate the array:

#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
...
}

This does print the JSON content: I've only used numberOfRowsInSection as a separate location for the NSLog statement.

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

回答1:

You are kicking off an asynch operation and then immediately trying to print out the contents. Move your first NSLog statement into the success block.

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");