2

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?

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

1 Answers1

2

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
  • Notification action methods must have one parameter, the notification object. – jscs Jan 19 '12 at 22:11
  • 1
    @JoshCaswell, Is that true? I thought that if you omitted the colon after the selector name when registering that you didn't need the parameter. I can't test that just now though... – Matt Wilding Jan 19 '12 at 22:49
  • @Josh Caswell nope. If you declare a method with less arguments as needed, it's not a problem. Due to the C function calling convention, the parameters are on the top of the stack when calling, and a function can pop them one-by-one, until it "runs out of arguments". So the only true problem is when you use more arguments than possible. –  Jan 20 '12 at 06:16
  • The [documented interface](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNotificationCenter/addObserver:selector:name:object): "The method specified by `notificationSelector` must have one and only one argument (an instance of `NSNotification`)." @Matt – jscs Jan 20 '12 at 06:43
  • and what if it doesn't have one? Since in that case you won't do anything with arguments... (I know we have to do things as the docs say, but even then, it's possible and, while not elegant, still valid). –  Jan 20 '12 at 10:40