findObjectsInBackgroundWithBlock: gets data from Parse, but data only exists inside the block

The last NSLog(@"The dictionary is %@", self.scoreDictionary) statement does not actually execute after the block completes. It executes after the findObjectsInBackgroundWithBlock method returns. findObjectsInBackgroundWithBlock presumably runs something in a separate thread, and your block may not actually execute at all until some length of time after that last NSLog statement. Graphically, something like this is probably happening:

Thread 1 
--------
retriveDataFromParse called
invoke findObjectsInBackgroundWithBlock
findObjectsInBackgroundWithBlock queues up work on another thread
findObjectsInBackgroundWithBlock returns immediately      |
NSLog statement - self.scoreDictionary not yet updated    |
retriveDataFromParse returns                              |
.                                                         V
.                       Thread 2, starting X milliseconds later
.                       --------
.                       findObjectsInBackgroundWithBlock does some work
.                       your block is called
.                       for-loop in your block
.                       Now self.scoreDictionary has some data
.                       NSLog statement inside your block

You probably want to think about, what do you want to do with your scoreDictionary data after you have retrieved it? For example, do you want to update the UI, call some other method, etc.? You will want to do this inside your block, at which point you know the data has been successfully retrieved. For example, if you had a table view you wanted to reload, you could do this:

for (PFObject *object in objects){
    ....
}
dispatch_async(dispatch_get_main_queue(), ^{
    [self updateMyUserInterfaceOrSomething];
});

Note the dispatch_async – if the work you need to do after updating your data involves changing the UI, you’ll want that to run on the main thread.

Leave a Comment