Reputation: 126319
Is it possible to list all the notifications that an object is observing via NotificationCenter
?
Upvotes: 3
Views: 681
Reputation: 31016
You could do it by parsing [[NSNotificationCenter defaultCenter] debugDescription]
and searching for object addresses:
Upvotes: 2
Reputation: 15784
I think it's possible with a "hacky" way: using Swizzling to observe the NSNotificationCenter.addObserver
method.
@implementation NSNotificationCenter (Swizzling)
+ (void)load {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
Class class = [self class];
SEL originalSelector = @selector(addObserver:selector:name:object:);
SEL swizzledSelector = @selector(swizzling_addObserver:selector:name:object:);
Method originalMethod = class_getInstanceMethod(class, originalSelector);
Method swizzledMethod = class_getInstanceMethod(class, swizzledSelector);
BOOL didAddMethod =
class_addMethod(class,
originalSelector,
method_getImplementation(swizzledMethod),
method_getTypeEncoding(swizzledMethod));
if (didAddMethod) {
class_replaceMethod(class,
swizzledSelector,
method_getImplementation(originalMethod),
method_getTypeEncoding(originalMethod));
} else {
method_exchangeImplementations(originalMethod, swizzledMethod);
}
});
}
- (void)swizzling_addObserver:(id)observer selector:(SEL)aSelector name:(NSNotificationName)aName object:(id)anObject {
//implement code here to store all notifications.
//then call original method (read in the link below to understand why we call **swizzling_addObserver** but not **addObserver**
[self swizzling_addObserver:observer selector:aSelector name:aName object:anObject];
}
To learn more about swizzling, you can read this post: http://nshipster.com/method-swizzling/
Upvotes: 0