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

后端 未结 2 1233
渐次进展
渐次进展 2020-11-27 07:57

I made the following test class to try out retrieving data from Parse:

-(void)retrieveDataFromParse
{
    PFQuery *query = [PFQuery queryWithClassName:@\"Tes         


        
相关标签:
2条回答
  • 2020-11-27 08:19

    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.

    0 讨论(0)
  • 2020-11-27 08:21

    The last NSLog(@"The dictionary is %@", self.scoreDictionary) is executed before the completion block executes. By the time, self.scoreDictionary will be empty for sure.

    Besides, the completion block will be executed on main thread. You can refer to the following link.

    https://parse.com/questions/what-thread-does-findobjectsinbackgroundwithblock-complete-on

    0 讨论(0)
提交回复
热议问题