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

时间:2013-11-15 08:10:04

标签: ios objective-c multithreading cocoa-touch parse-platform

我正在使用Parse来存储我的数据。在我的AppDelegate中,我想从服务器获取所有数据,然后将它们共享给我的ViewController,但我无法做到。因为我的MainThread总是在我的收集数据线程之前完成。有没有办法首先获取所有数据,或等待数据线程完成然后执行Mainthread,或其他方式来实现它。

这是我的代码:

@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;
    }

我的输出

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

我想要“outside block author = 4”但是>。<

2 个答案:

答案 0 :(得分:1)

你不应该或试图阻止主线程。该块的重点在于它是一个异步过程,你应该处理它。

正确的方法是:

获取app委托中的数据,然后在成功块中获取视图控制器并将数据传递给它。

或者:

将逻辑移动到视图控制器,以便在显示时确定是否需要获取数据并管理下载,然后更新其UI。

答案 1 :(得分:0)

我弄清楚解决方案是什么,我决定不使用findObjectsInBackgroundWithBlock但只使用findobject,所以这个方法将运行同步。 authors = [query findObjects];