0

I dont know what the deal with parse is but for some reason it wont allow me to save the retrieved array into a mutable array I created. It works inside the parse code block but once outside, it displays null. Help please?

 PFQuery *query = [PFQuery queryWithClassName:@"comments"];
    [query whereKey:@"flirtID" equalTo:recipe.flirtID];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {


            comments = [[NSMutableArray alloc]initWithArray:objects];

            // Do something with the found objects
            for (PFObject *object in objects) {

            }
        } else {
            // Log details of the failure
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
    NSLog(@"%@",[comments objectAtIndex:0]);
user3926564
  • 105
  • 1
  • 1
  • 6
  • The `comments` array is initialised and got values inside the completion block of `findObjectsInBackgroundWithBlock:`. Do the stuff with `comments` array inside that block. And the `NSLog(@"%@",[comments objectAtIndex:0]);` will be executed before completion of findobjects. So u get null. – Akhilrajtr Aug 18 '14 at 04:31

1 Answers1

1

It's actually working as it should. You should read up on how blocks work.

Edit: Try reading Apple's Documentation

You're NSLogging 'comments' before comments actually gets set. How does that work? You see, query is running in the background, and it will actually take a bit of time. It's running asynchronously. But the code outside the block will run immediately.

While the code comes before, because it's an asynchronous block, it can and will be run whenever.

Try this:

comments = [[NSMutableArray alloc]initWithArray:objects];
NSLog(@"%@",[comments objectAtIndex:0]);

The important question is, what do you want to do after the query? Looks like you want to save comments, but then what? That will determine what you do next.

Daniel Brim
  • 507
  • 3
  • 10
  • I understand your answer but what I want to be able to do is get that data into an array to populate a tableview down below at indexPathForRow block or just for later use – user3926564 Aug 18 '14 at 04:44
  • Okay, good start. comments should be a property. Once you've set comments, [self.tableView reloadData]; Then in your indexPathForRow method, pull from comments. – Daniel Brim Aug 18 '14 at 05:13