我正在使用 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”但是 >.<
最佳答案
你不应该想要或试图阻塞主线程。该 block 的全部意义在于它是一个异步过程,您应该处理它。
正确的做法是:
在应用程序委托(delegate)中获取数据,然后在成功 block 中获取 View Controller 并将数据传递给它。
或者:
将逻辑移至 View Controller ,以便在显示时决定是否需要获取数据并管理下载,然后更新其 UI。
关于ios - 如何等待 findObjectsInBackgroundWithBlock(在 Parse 中)完成然后运行 MainThread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19996370/