NS观察员通知的通知顺序

如果我有几个class级观察特定的NSNotification,通知发布时通知观察员的顺序是什么?

无法保证发送通知的顺序。 如果您需要订购,您可能需要创build一个类来侦听一个通知,并发出多个其他类可以侦听的有序通知。

订单是未定义的。 苹果pipe理着观察者列表,每当发布通知时,他们遍历列表并通知每个注册的观察者。 这个列表可能是一个数组或字典或者完全不同的东西(例如一个结构链表),而且由于观察者可以随时在运行时添加和删除,因此列表也可能随时更改,因此即使您知道如何该列表目前正在执行,您不能依赖任何特定的顺序。 进一步的任何OS X更新可能会导致列表内部的变化,10.7的情况可能不适用于10.8或10.6。

我已经testing过了,它看起来像通过addObserver方法sorting的对象

该testing的Consol输出是:

 2016-04-04 22:04:02.627 notificationsTest[1910:763733] controller 8 2016-04-04 22:04:02.629 notificationsTest[1910:763733] controller 1 2016-04-04 22:04:02.629 notificationsTest[1910:763733] controller 2 

AppDelegate.m

 #import "AppDelegate.h" #import "ViewController.h" #include <stdlib.h> @interface AppDelegate () @property (strong, readwrite, nonatomic) NSTimer *timer; @property (strong, readwrite, nonatomic) NSMutableArray *array; @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.array = [NSMutableArray array]; ViewController *vc3 = [ViewController new]; vc3.index = 8; ViewController *vc1 = [ViewController new]; vc1.index = 1; ViewController *vc2 = [ViewController new]; vc2.index = 2; [self.array addObject:vc1]; [self.array addObject:vc3]; [self.array addObject:vc2]; self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(sendNotification:) userInfo:nil repeats:YES]; return YES; } - (void)sendNotification:(NSNotification *)notification { [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTitle1 object:nil]; } @end 

ViewController.m

 #import "ViewController.h" #import "AppDelegate.h" @interface ViewController () @property (assign, readwrite, nonatomic) NSInteger index; @end @implementation ViewController - (instancetype)init { self = [super init]; if (self) { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondToNotification:) name:kNotificationTitle1 object:nil]; } return self; } - (void)respondToNotification:(NSNotification *)notification { NSLog(@"controller %ld", self.index); } @end