NSNotification在超级课程中观察并在超级和儿童班级中进行处理

时间:2012-01-19 21:13:41

标签: objective-c ios inheritance nsnotifications deterministic

我有一个观察NSNotification的课程ParentClass。 ParentClass处理通知。 ChildClass继承ParentClass并处理通知。 通知的发送顺序是否具有确定性?

换句话说,ParentClass是否总是在ChildClass之前处理通知,反之亦然?

1 个答案:

答案 0 :(得分:2)

这取决于实例化哪些类以及如何形成实际对象。它还取决于子类是否调用super进行处理。否则,正如NSNotificationCenter的文档所说,接收通知的对象的顺序是随机的,并且不依赖于您是子类还是超类。请考虑以下示例以便更好地理解:(需要几个示例,因为您的解释并不完全清楚):

示例1:两个不同的对象

ParentClass *obj1 = [[ParentClass alloc] init];
ChildClass *obj2 = [[ChildClass alloc] init];
// register both of them as listeners for NSNotificationCenter
// ...
// and now their order of receiving the notifications is non-deterministic, as they're two different instances

示例2:子类调用super

@implementation ParentClass

- (void) handleNotification:(NSNotification *)not
{
    // handle notification
}

@end

@ipmlementation ChildClass

- (void) handleNotification:(NSNotification *)not
{
    // call super
    [super handleNotification:not];
    // actually handle notification
    // now the parent class' method will be called FIRST, as there's one actual instace, and ChildClass first passes the method onto ParentClass
}

@end