观察者通知的NSNotification顺序

时间:2012-10-18 14:55:24

标签: objective-c ios nsnotificationcenter

如果我有几个类观察特定的NSNotification,那么观察者在发布通知时会以什么顺序通知?

3 个答案:

答案 0 :(得分:19)

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

答案 1 :(得分:6)

订单未定义。 Apple管理观察员列表,每当发布通知时,他们都会遍历列表并通知每个注册的观察者。列表可以是数组或字典或完全不同的字体(例如结构的链接列表),并且由于观察者可以在运行时随时添加和删除,因此列表也可能随时更改,因此即使您知道如何该列表目前已实施,您永远不能依赖任何特定订单。此外,任何OS X更新都可能导致列表内部更改,10.7的实际情况可能不适用于10.8或10.6。

答案 2 :(得分:1)

我测试了它,看起来对象是按 addObserver 方法

排序的

此测试的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