The NSNotificationCenter
and gcd
& dispatch_get_main_queue()
服务于截然不同的目的。我不认为“vs”真正适用。
NSNotificationCenter
提供了一种分离应用程序不同部分的方法。例如kReachabilityChangedNotification
Apple的Reachability示例代码中当系统网络状态发生变化时发布到通知中心。反过来,您可以要求通知中心调用您的选择器/调用,以便您可以响应此类事件。(想想空袭警报器)
gcd
另一方面,提供了一种快速分配要在您指定的队列上完成的工作的方法。它可以让您告诉系统您的代码可以在哪些点被单独剖析和处理,以利用多线程和多核 CPU。
通常(几乎总是)通知是在发布通知的线程上观察到的。除了一个 API 的显着例外......
这些概念交叉的一个 API 是NSNotificationCenter
's:
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
作为我更改视图控制器视图背景颜色的信号。但它发布在后台线程上。好吧,我可以使用前面提到的 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 的主要优点似乎是你的观察块将在postNotification...
称呼。如果您使用标准 API 并实施observeHeyNotification:
如下所示,无法保证执行调度块之前需要多长时间:
-(void)observeHeyNotification:(NSNotification *)note{
dispatch_async(dispatch_get_main_queue(), ^{
// Same stuff here...
});
}
当然,在此示例中,您可以简单地不在后台线程上发布通知,但是如果您使用的框架无法保证它将在哪个线程上发布通知,那么这可能会派上用场。