简体   繁体   中英

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

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.

You should be able to use [addObserver:self selector:@selector(whatever:) name:nil object:nil] and just put your logging code in the whatever: method. This observer should get all notifications posted by your app (at least all those posted by the default center).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM