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

FindObjectsInBackgroundWithBlock Help??

Can someone please tell me what i am doing wrong, and why I keep getting a (null) outside of the block??

Heres my code:
.m

  • (void)viewDidLoad { [super viewDidLoad];

    PFQuery *query = [PFUser query];
    [query whereKey:@"selectedGym" equalTo:gymLabelText];
    

    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)

     {
    
         self.gymRoster=objects;
    
     }];
    

    NSLog(@"%@",gymRoster);

Not to mention but I also set it up the same way as the EditFriendsViewController as in the treehouse project and I still got a null.

1 Answer

- (void)viewDidLoad {
    [super viewDidLoad];

    PFQuery *query = [PFUser query];
    [query whereKey:@"selectedGym" equalTo:gymLabelText];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.gymRoster=objects;
    }];

    NSLog(@"%@",gymRoster);
}

If your code is like the code above (just wanted to copy and paste to confirm the formatting) then your issue has to do with the query running in the background. When you call findObjectsInBackgroundWithBlock, you're telling Parse to run the given query, and execute the block that you pass in once the query finishers. In this case, you're telling Parse to go execute this query, and when it's done set your gymRoster instance variable to be the result. The reason your NSLog is always nil is because the NSLog is executing before the query finishes. Remember that you should put all code you want to be executed when the query finishes inside the block you pass in. You can't assume that the query will finish by the time you get to the NSLog since the query is executing in the background!