如果我有多个类在观察特定的 NSNotification,那么当该通知被发布时,观察者的通知顺序是什么?
无法保证通知的发送顺序。如果您需要排序,请创建一个监听单个通知并发送多个有序通知供其他类侦听的类。
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
NSNotificationCenter
内部,并且将来可能会更改。 - atxe