2012-06-07 98 views
1

我遇到了一些與我的代碼有關的問題,不確定如何加快速度。下面是從應用程序委託(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圖片。正如你所看到的,當所有這些下載完成後,refreshView方法在我的視圖控制器中被觸發。

加載完成後重新加載我有NSLog(@「%@」,@「Finished reloading ..」);所以我知道什麼時候視圖重新加載。

問題:

所以我期待在控制檯:

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秒前。

接下來你會做什麼?

回答

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將不會更新,直到主隊列塊完成。

+0

w0w優秀的答案我想我還在學習基礎知識..缺少一些基礎知識。謝謝 – London

+0

'[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@「initialized」];'這部分是否在正確的位置?此外,布拉克似乎有點。 – Peres