ios - NSNotification 与 dispatch_get_main_queue

标签 ios grand-central-dispatch nsnotifications

关于this question我想知道关于何时使用 NSNotification(在主线程中有观察者)与使用 GCD 将工作从后台线程分派(dispatch)到主线程,是否有任何普遍接受的逻辑?

似乎使用通知观察器设置,您必须记住在 View 卸载时拆除观察器,但随后您可靠地忽略了通知,因为将作业分派(dispatch)到主线程可能会导致在以下情况下执行 block View 已卸载。

因此,在我看来,通知应该提供改进的应用程序稳定性。根据我所读的 GCD,我假设调度选项提供了更好的性能?

更新:

我知道通知和调度可以一起愉快地工作,在某些情况下,应该一起使用。我试图找出是否存在应该/不应该使用的特定情况。

一个例子:为什么我要选择主线程来触发来自分派(dispatch) block 的通知,而不是仅仅分派(dispatch)主队列上的接收函数? (显然这两种情况的接收函数会有一些变化,但最终结果似乎是一样的)。

最佳答案

NSNotificationCentergcd & dispatch_get_main_queue() 有非常不同的用途。我不认为“vs”是真正适用的。

NSNotificationCenter 提供了一种分离应用程序不同部分的方法。例如Apple的Reachability示例代码中的kReachabilityChangedNotification是在系统网络状态发生变化时发布到通知中心的。反过来,您可以要求通知中心调用您的选择器/调用,以便您可以响应此类事件。(想想空袭警报器)

另一方面,

gcd 提供了一种快速分配要在您指定的队列上完成的工作的方法。它可以让您告诉系统您的代码在哪些点可以被单独剖析和处理,以利用多线程和多核 CPU。

通常(几乎总是)在发布通知的线程上观察到通知。除了一个 API 的显着异常(exception)...

这些概念相交的 API 是 NSNotificationCenter 的:

addObserverForName:object:queue:usingBlock:

这本质上是一种确保在给定线程上观察到给定通知的便捷方法。尽管“usingBlock”参数泄露了它在幕后使用 gcd

下面是它的用法示例。假设在我的代码中某处有一个 NSTimer 每秒调用此方法:

-(void)timerTimedOut:(NSTimer *)timer{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // Ha! Gotcha this is on a background thread.
        [[NSNotificationCenter defaultCenter] postNotificationName:backgroundColorIsGettingBoringNotification object:nil];
    });
}

我想使用 backgroundColorIsGettingBoringNotification 作为我更改 View Controller View 背景颜色的信号。但它发布在后台线程上。好吧,我可以使用上述 API 仅在主线程上进行观察。注意下面代码中的viewDidLoad:

@implementation NoWayWillMyBackgroundBeBoringViewController {
    id _observer;
}
-(void)observeHeyNotification:(NSNotification *)note{
    static NSArray *rainbow = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        rainbow = @[[UIColor redColor], [UIColor orangeColor], [UIColor yellowColor], [UIColor greenColor], [UIColor blueColor], [UIColor purpleColor]];
    });
    NSInteger colorIndex = [rainbow indexOfObject:self.view.backgroundColor];
    colorIndex++;
    if (colorIndex == rainbow.count) colorIndex = 0;
    self.view.backgroundColor = [rainbow objectAtIndex:colorIndex];
}
- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor redColor];
    __weak PNE_ViewController *weakSelf = self;
    _observer = [[NSNotificationCenter defaultCenter] addObserverForName:backgroundColorIsGettingBoringNotification
                                                                  object:nil
                                                                   queue:[NSOperationQueue mainQueue]
                                                              usingBlock:^(NSNotification *note){
                                                                  [weakSelf observeHeyNotification:note];
                                                              }];
}
-(void)viewDidUnload{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:_observer];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:_observer];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end

此 API 的主要优点似乎是您的观察 block 将在 postNotification... 调用期间被调用。如果您使用标准 API 并实现 observeHeyNotification: 如下所示,则无法保证在执行分派(dispatch) block 之前需要多长时间:

-(void)observeHeyNotification:(NSNotification *)note{
    dispatch_async(dispatch_get_main_queue(), ^{
        // Same stuff here...
    });
}

当然,在此示例中,您可以简单地不在后台线程上发布通知,但如果您使用的框架无法保证它将在哪个线程上发布通知,这可能会派上用场。

关于ios - NSNotification 与 dispatch_get_main_queue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13481716/

相关文章:

ios - 核心数据不直接保存到 sqlite

ios - 在 iOS 上,您能否发出同步网络请求(但不在主线程上)并仍然获得进度回调(在单独的非主线程上)?

ios - 杀死一个用 dispatch_sync 锁定的线程

objective-c - NSBlockOperation 的粒度状态

ios - SVProgressHUD 在显示另一条消息后不显示

ios - UIScrollView 1D 弹跳但 2D 滚动

ios - 使用 usersdefault 快速保存数据的排行榜

swift - Linux 中的异步 Swift 处理不起作用

ios - NSNotification 监听器 iOS

macos - QTCaptureDeviceWasConnectedNotification