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

My array keeps returning null even though there are objects in it when I NSLog it to the console. Any ideas?

I'm using the Parse query located in the Ribbit app to find messages that are sent to the current user of the app. I am not loading the messages into a tableview however. I want to do something else with them in another part of my code. Regardless, when I NSLog, my "self.messages" array within the block, it returns that there are messages that have been found, and loads them into the array. When I try accessing the self.messages array in another part of my code, however, it returns null. If someone has a solution that would be fantastic! I think it has to do with the asynchronous block call, but I don't know how to fix it. My code is below:

PFQuery *query = [PFQuery queryWithClassName:@"Messages"];
    [query whereKey:@"recipientIds" equalTo:[[PFUser currentUser] objectId]];
    [query orderByDescending:@"createdAt"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
        else {
            self.messages = objects;
            NSLog(@"Retrieved %d messages", [self.messages count]);
        }
    }];

3 Answers

Misha Shaposhnikov
Misha Shaposhnikov
8,718 Points

Perhaps, the asynchronous callback is running after your other code, so the self.messages is still null. Try putting a simple

if( ! self.messages == null)

to wait for the asynchronous callback to finish.

Forgot to best answer this...sorry :)....better late than never I suppose! Fixed my problem beautifully btw. Thanks!

Lee Hardy
Lee Hardy
5,407 Points

Sounds like Misha might be right in the above.

Could be worth putting a call to your method within the else clause of the if statement, that way your method is only called when the async callback is completed, though this does depend on what you are trying to do in your app

Calvin Nix
Calvin Nix
43,828 Points

Hey Chris,

This is most likely due to an issue with timing. I see this a lot when people are using asynchronous threads. You definitely want to implement a check like the one Misha has provided just to avoid any unforeseen errors that might arise by passing a null value.

Thanks, Calvin