繁体   English   中英

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

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

我正在使用解析来存储我的数据。 在我的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

我希望我的“外部区块作者= 4”,但>。<

您不希望或尝试阻塞主线程。 该块的全部要点是它是一个异步过程,您应该对其进行处理。

正确的方法是:

在应用程序委托中获取数据,然后在成功块中获取视图控制器并将其传递给数据。

要么:

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

我想出了什么解决方案,所以我决定不使用findObjectsInBackgroundWithBlock而是仅使用findobject,因此此方法将同步运行。 authors = [query findObjects];

暂无
暂无

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

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