0

I have the following code which is loading a list of users from Parse into an array named users:

PFUser *currentUser = [PFUser currentUser];
NSString *currentUserUni = currentUser[@"university"];

//Parse Query
//-------------------------------------------
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"university" equalTo:currentUserUni];
[query setLimit:50];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        [users removeAllObjects];
        [users addObjectsFromArray:objects];



}];

But if I try to call users outside of that closing bracket at the end, it is nil. Does anyone know 1)what would be causing this? and 2)How can I get the values into an array that can be accessed outside of that closing bracket?

Benjamin Porter
  • 447
  • 2
  • 7
  • 18

2 Answers2

1

1) findObjectsInBackgroundWithBlock retrieves objects in the background, meaning, it happens asynchronously - the method runs while other processes are running instead of sequentially. So say you have your current code:

Note I would, supply an error check before messing with your users array.

PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"university" equalTo:currentUserUni];
[query setLimit:50];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
    if (!error) {
        [users removeAllObjects];
        [users addObjectsFromArray:objects];
    } else {
      // show your alert message
    }
}];


... some code that comes after the block ...

The "... some code that comes after the block ..." portion of your 'class' or 'method' will be running while your searching for the objects in the background...

2) What needs to be done to solve your issue is add the __block keyword to your users array.

Heres a reference to an answer in stack overflow that further explains the __block keyword.

__block keyword

Community
  • 1
  • 1
jsetting32
  • 1,632
  • 2
  • 20
  • 45
1

takeing jsetting32 answer and changing it

i think you should take removeAllObjects out of the loop

[users removeAllObjects];
PFQuery *query = [PFQuery queryWithClassName:@"_User"];
[query whereKey:@"university" equalTo:currentUserUni];
[query setLimit:50];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {

    [users addObjectsFromArray:objects];
} else {
  // show your alert message
}
}];


... some code that comes after the block ...
KennyVB
  • 745
  • 2
  • 9
  • 28
  • Issue is when doing this is if the query fails, then he may want to keep the list of currently loaded users within his array. So you only remove the elements in the array if the query succeeds... But whatever the user wants to do, he can do either solution – jsetting32 Jan 06 '15 at 02:45