Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Class methods problem

Hey guys, I was recent making a small app and I ran into this massive problem where I don't have any idea what's happening. This problem is that there is an method that has a return type of a NSDictionary this dictionary is returned as the serialised version of the JSON data. The code for the problem is attached below.

View will appear code:-

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.tabBarController.tabBar.hidden = NO;

    NSDictionary *dictionary = [self getProductForCategory:2];
    NSLog(@"%@", dictionary);

}

//Method that i was taking about code:-
- (NSDictionary *)getProductForCategory:(int)category
{
        static NSDictionary *returnDictionary = nil;
        NSURLSession *session = [NSURLSession sharedSession];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://example.com/GetProduct.php?cat=%d", category]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
            if (!error) {
                NSData *data = [[NSData alloc] initWithContentsOfURL:location];
                NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

                    returnDictionary = [[NSDictionary alloc] initWithDictionary:response];
                //NSLog(@"%@", returnDictionary);
            }
            else
            {
                NSLog(@"Error: \n %@", error);
            }
        }];
    [task resume];
    return returnDictionary;
}

1 Answer

The problem is that your download task where you get the dictionary data from whatever server you're using runs asynchronously, which means the rest of your method moves on before it's done. That means when your method returns returnDictionary, returnDictionary hasn't been set to the JSON data yet, and is still nil

How do i get out of this problem ?