Search code examples
iosobjective-cjsonxcodeafnetworking-2

AFNetworking + AFHTTPRequestOperation not being able to save Array


So I am trying to access a json file online and I can get the contents of the JSON file when I run the completion block using AFHTTPRequestOperation method. But when I try to NSLog outside the completion block, it becomes null. I was wondering why this is happening and how I would go about fixing this. Below is the code I have so far:

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCredential:credentials];
    [operation setResponseSerializer:[AFJSONResponseSerializer alloc]];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
        jsonOutputData = [NSMutableArray arrayWithObject:responseObject];
        self.newsFeedArray = [NSMutableArray arrayWithArray:[jsonOutputData copy]];


    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        NSLog(@"Failure: %@", error);
    }];

    [manager.operationQueue addOperation:operation];
    NSLog(@"%@", self.newsFeedArray);

The NSLog with Success shows the JSON but the NSLog with the self.newsFeedArray shows (null). I am just wondering why this is happening. If you need more clarification, let me know. Any help would be appreciated!

Thanks!


Solution

  • The success and failure blocks get called asynchronously. So self.newsFeedArray simply has not been set yet at the time of the last NSLog call, because the operation has not completed.

    You could wait for the operation to complete (e.g., [operation waitUntilFinished]) but you almost certainly don't want to do this, especially on the main thread. Rather have the completion blocks trigger the desired behaviour.