NSNotification观察者通知的顺序

23
如果我有多个类在观察特定的 NSNotification,那么当该通知被发布时,观察者的通知顺序是什么?

2
我相信他们接收通知的顺序与添加观察者的顺序相同。无论如何,我不会依赖这个事实,因为这涉及到NSNotificationCenter内部,并且将来可能会更改。 - atxe
3个回答

23

无法保证通知的发送顺序。如果您需要排序,请创建一个监听单个通知并发送多个有序通知供其他类侦听的类。


1
你怎么知道通知发送的顺序没有保证?这在苹果的文档中有写吗? - ma11hew28
1
@ma11hew28,没有明确说明是否有顺序,也没有说明是否有顺序(这就是为什么我说没有保证)。由于没有任何信息表明它们是有序的或无序的,因此您必须假设它们可能是无序的,即使它们当前似乎每次都像有序的一样运行... - Kendall Helmstetter Gelner
好的。谢谢,肯德尔。 - ma11hew28

7
订单未定义。苹果公司管理观察者列表,每当通知发布时,它们会遍历列表并通知每个已注册的观察者。该列表可以是数组、字典或完全不同的结构(例如结构体的链表)。由于观察者可以在运行时随时添加和删除,因此列表也可能随时发生更改,因此即使您知道当前如何实现列表,也不能依赖任何特定的顺序。此外,任何 OS X 更新都可能导致列表内部发生变化,并且适用于10.7的规则可能不适用于10.8或10.6。

1
你怎么知道顺序是未定义的?苹果的文档中有写吗? - ma11hew28
1
@ma11hew28 这个道理也适用于另一方面:所有的东西都是未定义的,除非它们在某个地方被定义了。你不需要明确地取消定义,而是需要明确地定义它们。由于苹果公司在文档中没有定义顺序,因此顺序自动变成了未定义的。 - Mecki
好的。谢谢,@Mecki。 - ma11hew28

1
我已经测试过了,看起来对象是按照addObserver方法排序的。
此测试的控制台输出为:
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接