Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve all NSNotificationCenter observers?

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.)

like image 707
Ortwin Gentz Avatar asked Nov 07 '12 14:11

Ortwin Gentz


People also ask

Do I need to remove observers Swift?

As of iOS 9 (and OS X 10.11), you don't need to remove observers yourself, if you're not using block based observers though. The system will do it for you, since it uses zeroing-weak references for observers, where it can.

What is Nsnotification name?

A structure that defines the name of a notification.

What is NotificationCenter default addObserver?

NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: nil) This adds an observer with those parameters to the Notification Center, essentially telling it that self wants to observe for notifications with name .


2 Answers

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
...
like image 60
Ortwin Gentz Avatar answered Oct 21 '22 23:10

Ortwin Gentz


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

like image 1
Tomasz Zabłocki Avatar answered Oct 21 '22 21:10

Tomasz Zabłocki