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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With