简体   繁体   English

如何等待findObjectsInBackgroundWithBlock(在Parse中)完成,然后运行MainThread?

[英]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. 在我的AppDelegate中,我想从服务器获取所有数据,然后将它们共享到ViewController,但是我做不到。 Because my MainThread always finish before my collect data thread. 因为我的MainThread总是在收集数据线程之前完成。 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. 有什么方法可以首先获取所有数据,或者等待数据线程完成然后再执行Mainthread,或者采用另一种方法来实现此目的。

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 >.< 我希望我的“外部区块作者= 4”,但>。<

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. 将逻辑移至视图控制器,以便在显示逻辑时决定是否需要获取数据,并管理下载,然后更新其UI。

I figured out what is the solution, I decided not use findObjectsInBackgroundWithBlock but to use findobject only, so this method will run synchronous. 我想出了什么解决方案,所以我决定不使用findObjectsInBackgroundWithBlock而是仅使用findobject,因此此方法将同步运行。 authors = [query findObjects];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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