13

I'd like to retrieve a list of observers (objects and selectors) for a given notification name. I know there's no official API for that. I also know I could subclass NSNotificationCenter to accomplish this. Sometimes however this is not a viable option because NSNotificationCenter usage is spread all over the code or even binary frameworks.

So I'm looking for an unofficial/private way to do this. (Since it's about debugging only, that's fine.)

Community
  • 1
  • 1
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
  • You may just want to swizzle the methods so you get the object: http://cocoadev.com/wiki/MethodSwizzling – rckoenes Nov 07 '12 at 14:14
  • here is an answer which implements swizzling to track observers http://stackoverflow.com/questions/10346700/nsnotificationcenter-list-of-observers/34692724#34692724 – Zayin Krige Jan 09 '16 at 11:32

2 Answers2

19

Finally, Apple added a way to print all notification center observers:

po [NSNotificationCenter defaultCenter]

It prints a comma separated list with Name, Object, Observer, and Options:

<NSNotificationCenter:0x7f997b307500>
Name, Object, Observer, Options
WebPreferencesRemovedNotification, 0x11165b680, 0x116c87ff8, 1400
UIApplicationWillEnterForegroundNotification, 0x11165b680, 0x7f997a838000, 1400
...
Ortwin Gentz
  • 52,648
  • 24
  • 135
  • 213
1

If you don't want to subclass NSNotificationCenter you can rename original addObserver:selector:name:object method and create your own with such name and add observers in there to some array then call original renamed method.

Take a look at following methods: class_addMethod, class_replaceMethod, class_getMethodImplementation.

Also look at this SO question: Method Swizzling

I am not sure why you want observers but you might find this class useful, which removes observers automatically for you which I think might be what you want. SFObservers

Community
  • 1
  • 1
Tomasz Zabłocki
  • 1,326
  • 7
  • 14