2011-03-13 54 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

相关问题