2011-03-13 74 views
2

由於NSNotification在除主線程以外的線程上調用其選擇器,我注意到您對UIView或其他界面元素作出的任何響應該通知的更改往往生效緩慢。如果主線程很忙(這是我的經常做的),這是最嚴重的。在響應NSNotifications時,更新UIViews的最佳做法是什麼

我可以通過調用「performSelectorOnMainThread:」來解決這個問題。這真的是最佳做法嗎?

- (void) gotMovieSaveFinishNotication: (NSNotification *) not { 
NSURL *exportMovieURL = (NSURL *) [not object]; 
//saving the composed video to the photos album 
ALAssetsLibrary* library = [[[ALAssetsLibrary alloc] init] autorelease]; 

if(![library videoAtPathIsCompatibleWithSavedPhotosAlbum: exportMovieURL]) { 
    NSLog(@"videoAtPathIsCompatibleWithSavedPhotosAlbum fails for: @",exportMovieURL); 
    return; 
} 

[library writeVideoAtPathToSavedPhotosAlbum:exportMovieURL 
          completionBlock:^(NSURL *assetURL, NSError *error) 
{ 
    [self performSelectorOnMainThread:@selector(setTintToNormal) 
          withObject: NULL 
         waitUntilDone: YES]; 

    if(error) 
    { 
     DLog(@"The video saving failed with the following error =============== %@",error);//notify of completion 
    } 
    else 
    { 
     DLog(@"The video is saved to the Photos Album successfully"); 

    } 


}]; 

}

回答

3

NSNotificationCenter在您調用postNotification的同一線程上發送通知!所以它可能是主線程或後臺線程。

順便說一句,你不應該從非主線程中對UI進行更改,完全停止 - 這甚至不是一個緩慢的問題,你只是不應該這樣做,事情可能會崩潰等等。

您的解決方案當然是可行的,但有一個稍微不同(可能更好)的方式。通過實際調用方法來生成主線程通知

http://www.cocoanetics.com/2010/05/nsnotifications-and-background-threads/

總之,在這個問題上面的鏈接交易的方法,通過在一個類別的一些方便的輔助方法:對信息見本頁面。可能有用!從實際通知收據方式中調用performSelectorOnMainThread的解決方案感覺有點「整潔」,因爲使用您當前的技術,您最終可能會收到大量performSelectorOnMainThread調用,無論您在應用中收到通知。

此外,這是有用的信息:

http://cocoadev.com/index.pl?NotificationsAcrossThreads

+0

感謝您提醒關於UIKit訪問主線程的危險。我已經閱讀過,但不知怎的,從來沒有認真對待:-)。現在我回到了直線和狹窄。 – 2011-03-14 19:34:07

+0

是的,我喜歡那個類別的解決方案。似乎最簡潔的方式,特別是因爲這是發生在多個地方。謝謝您的幫助! – 2011-03-14 19:35:02

2

是。所有與UI相關的方法只應在主線程中調用。

你有另一種選擇是使用GCD並將其發送到主隊列:

dispatch_async(dispatch_get_main_queue(), ^{ 
    // do some stuff on the main thread here... 

    [self setTintToNormal]; 
}); 

也考慮waitUntilDone:NO。只要有可能,不要阻塞。

+0

謝謝,我喜歡這個作爲一種替代的想法 - 但我與其他的想法(http://www.cocoanetics.com/去2010/05/nsnotifications和 - 背景線程/)。 – 2011-03-14 19:35:50

相關問題