我的代码遇到了一些问题,不知道如何加快速度。这是我来自应用程序委托的代码(didFinishLaunchingWithOptions方法体):
initialized = [[NSUserDefaults standardUserDefaults] boolForKey:@"initialized"];
if (!initialized) {
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[DAO setDocumentsCacheDirectory:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
....download images and files needed by application
NSLog(@"%@", @"Finished downloadding images and files");
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"initialized"];
});
}
当这种异步下载发生时,我的视图中有旋转的 gif 图像。如您所见,当所有这些下载完成后,刷新视图方法在我的视图控制器中被触发。
加载完成后,我有 NSLog(@"%@", @"完成重新加载..");所以我知道视图何时重新加载。
问题 :
所以我正在看控制台:
2012-06-07 12:52:34.898 TestApp[29800:13c03] Finished downloadding images and files
[Switching to process 29800 thread 0x13c03]
2012-06-07 12:52:34.909 TestApp[29800:13c03] Finished reloading..
文件下载似乎在一两秒内完成。然后,正如您在时间戳中看到的那样,视图重新加载立即完成。
但问题是应用程序等待 5 秒左右,我不知道在哪里发生了什么,只有这样视图才会重新刷新,尽管消息完成重新加载...... 大约在 5 秒前显示。
你接下来会怎么做?
您将通知发布在后台队列中 - 如果这是触发 UI 更新的原因,则需要在主队列上完成此操作:
dispatch_async(queue, ^{
[DAO setDocumentsCacheDirectory:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]];
....download images and files needed by application
NSLog(@"%@", @"Finished downloadding images and files");
dispatch_sync(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];
}
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"initialized"];
});
请注意,我在这里使用了dispatch_sync
...在主队列块完成之前,不会更新NSUserDefaults
。