سؤال

I have class ParentClass that observes an NSNotification. ParentClass handles the notification. ChildClass inherits ParentClass and also handles the notification. Is the order in which the notifications are delivered deterministic?

In other words will ParentClass always handle the notification before ChildClass or vice versa?

هل كانت مفيدة؟

المحلول

It depends on which classes are instantiated and how, forming actual objects. It also depends on whether the subclass calls super for handling. Otherwise, as NSNotificationCenter's docs say, the order of objects that receive the notifications is random, and does NOT depend on wheher you're a subclass or superclass. Consider the following samples for better understanding: (several examples are needed as your explication is not entirely clear):

Example 1: two different objects

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

Example 2: subclass calls 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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top