Yannis P.
Yannis P.

Reputation: 833

iOS Objective-C AFNetworking dataTaskWithRequest:completionHandler: can't retrieve data from inside completition block

Here is my code:

 //create array with all the teams
NSMutableArray *leagueTeams = [[NSMutableArray alloc] init];
//send request

[[sessionManager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
    NSDictionary *responseFromJSONDictionary = (NSDictionary *) responseObject;

    //copy the team's attributes into temp variables
    NSString *tempTeamIDCode = [responseFromJSONDictionary objectForKey:@"teamCode"];
    NSString *tempTeamName = [responseFromJSONDictionary objectForKey:@"teamName"];
    NSInteger tempTeamPoints = [(NSNumber *) [responseFromJSONDictionary objectForKey:@"teamPoints"] integerValue];

    //use temp variables to create a temporary team
    Team *aTeam = [[Team alloc] initWithTeamIdCode:tempTeamIDCode andTeamName:tempTeamName andLeaguePoints:tempTeamPoints];

    //add team to array
    [leagueTeams addObject:[aTeam copy]];

}]resume];

I am trying to make an app that retrieves JSON data from a server. for now I'm using a static JSON to retrieve entries. I used breakpoints to follow the variable values. The app successfully retrieves the JSON data, it successfully creates the 3 temp variables and successfully creates the team object AND successfully adds the object to the leageTeams mutablearray, while inside the success code block.

BUT, the moment the application leaves the success block, the leagueTeams array disappears. it doesn't exist in memory even as an empty array, like it did before the execution of the success block.

I'm probably doing something very wrong with trying to pass data to an outside variable inside the code block, but all other similar questions had the trouble of not getting the data from the server in time, but in my case the data request is always successful and the JSON response and turning it into an NSDICtionary all work fine....so anyone can help please? Thanks

Upvotes: 1

Views: 1505

Answers (1)

Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

Okay what's happening is the "dataTaskWithRequest:completionHandler:" method is asynchronous! Once it starts the program execution doesn't wait for it to return value it continues to next line outside of it. So probably the code which you have written below this method is executing first than the code inside the completion handler. So what you can do is trigger a Notification or call some delegate method to run any code after the completion Handler returns the required value.

Upvotes: 2

Related Questions