Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging NSNotifications

I would like to log any NSNotifications posted by a single NSNotificationCenter shared accross my application. I have tried subclassing NSNotificationCenter with the intention of adding logging code to the three post methods, but it returns an instance of CFNotification center instead of my subclass.

Surely there is a way of monitoring NSNotification posting?

EDIT/UPDATE

As two answers below correctly point out I could listen to all notifications and log them in a handler, but the sequence the handler would receive these notifications is far from guaranteed to be the same as the sequence in which they were dispatched. If I could be sure the handler would always be the first hander to be notified this would work, but I cannot: 'The order in which observers receive notifications is undefined' From NSNotification Docs

like image 281
Undistraction Avatar asked Apr 17 '12 15:04

Undistraction


1 Answers

By using - addObserver:selector:name:object: and passing nil for both the name and the object, you will get notified about any notification.

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(log:) name:nil object:nil];
    }
    return self;
}

- (void)log:(NSNotification *)notification
{
    NSLog(@"%@", notification);
}

Edit: if you want to get the real order of the notifications being send, try subclassing NSNotificationCenter and overriding the following methods:

– postNotification:
– postNotificationName:object:
– postNotificationName:object:userInfo:

If subclassing is no option for you, you might consider defining a category on NSNotificationCenter where you override these methods with calling the super implementation. (you will need to swizzle methods to call super within a category). Tell me if you need help doing so.

like image 189
Christian Schnorr Avatar answered Oct 23 '22 00:10

Christian Schnorr