Search code examples
iosobjective-ccocoa-touchinheritanceclass-cluster

Inherit from NSNotification


I want to create a subclass of NSNotification. I don't want to create a category or anything else.

As you may know NSNotification is a Class Cluster, like NSArray or NSString.

I'm aware that a subclass of a cluster class needs to:

  • Declare its own storage
  • Override all initializer methods of the superclass
  • Override the superclass’s primitive methods (described below)

This is my subclass (nothing fancy):

@interface MYNotification : NSNotification
@end

@implementation MYNotification

- (NSString *)name { return nil; }

- (id)object { return nil; }

- (NSDictionary *)userInfo { return nil; }

- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo
{
    return self = [super initWithName:name object:object userInfo:userInfo];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    return self = [super initWithCoder:aDecoder];
}

@end

When I use it, I get an extraordinary:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** initialization method -initWithName:object:userInfo: cannot be sent to an abstract object of class MYNotification: Create a concrete instance!'

What else do I have to do in order to inherit from NSNotification?


Solution

  • The problem was that was trying to call the superclass initialiser. You can't do that because is an abstract class. So, in the initializer you just have to init your storage.

    Because this is horrible, I end up creating a category for NSNotification instead. There I added three kind methods:

    • Static constructor for my custom notification: Here I configure userInfo to be used as the storage.
    • Method to add information to the storage: The notification observer will call this to update userInfo.
    • Method to process the information submitted by the observes: After the post method has finished, the notification has collected all the information needed. We just have to process it and return it. This is optional if you are not interested in collecting data.

    In the end, the category it's just a helper to deal with userInfo.

    Thanks @Paulw11 for your comment!