简体   繁体   中英

How to wait for findObjectsInBackgroundWithBlock (in Parse) finish then run the MainThread?

I am using Parse to store my data. In my AppDelegate I want to get all my data from server then shared them to my ViewController but I cant do it. Because my MainThread always finish before my collect data thread. Is there any way to get all data first, or wait for the data thread finish then do the Mainthread, or another way to implement this.

This is my code:

@synthesize authors;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [SCategory registerSubclass];
    [Parse setApplicationId:PARSE_APP_ID clientKey:PARSE_CLIENT_KEY];

     PFQuery *query = [SCategory query];

    // type =1 : programmes
   [query whereKey:@"type" equalTo:@1];
   [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {

            // The find succeeded.
            authors = [[NSMutableArray alloc] initWithArray:objects];
            NSLog(@"inside block author: %d",[authors count]);
       } else {
            // Log details of the failure
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];



   NSLog(@"outside block author: %d",[authors count]);

        return YES;
    }

My Output

2013-11-15 15:00:59.424 Sala[5340:70b] outside block author: 0
2013-11-15 15:01:00.804 Sala[5340:70b] inside block author: 4

I want my "outside block author = 4" but >.<

You should not want to or try to block the main thread. The whole point of the block is that it's an asynchronous process and you should deal with that.

The correct approach is to either:

Get the data in the app delegate and then, in the success block, get the view controller and pass it the data.

Or:

Move the logic to the view controller so that when it's shown it decides if it needs to get the data and it manages the download and then updates its UI.

I figured out what is the solution, I decided not use findObjectsInBackgroundWithBlock but to use findobject only, so this method will run synchronous. authors = [query findObjects];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM