Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to check if observer listens to some NSNotification?

I want to check if my view is listening for UIApplicationWillResignActiveNotification or not. If it is listening then I want to remove it during dealloc. Now I was wondering if there is way to do this using objective c ?

I am not trying avoid multiple additions for notifications. Here is bit more explanation of what I am trying to do.

I have custom gridView. I can initialize it with either scaling enabled or scaling disabled. If init with scaling enabled I add itself as observer of UIApplicationWillResignActiveNotification but if its init with scaling disabled then it does not add itself as an observer for that notification. Now, in dealloc I want to remove that gridView as an observer of that notification. So I was wondering if there is way to find out if gridView is listening to that notification or not.

like image 780
slonkar Avatar asked Oct 02 '22 16:10

slonkar


2 Answers

I don't know of any way to check what notifications your observer is listening for, but regardless of whether it's listening for UIApplicationWillResignActiveNotification or not, calling:

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification];

will cause self to stop listening for that notification, or do nothing if self is not listening for it.

Specifying the name of the notification you want to stop listening for is the best practice, but since you said you're putting this in dealloc, it would also be safe to just do this:

[[NSNotificationCenter defaultCenter] removeObserver:someObserver];
like image 72
BevTheDev Avatar answered Oct 07 '22 20:10

BevTheDev


If you want to check in dealloc method, if your view is registered as observer to correctly remove it - you should not. All you need to do is:

[[NSNotificationCenter defaultCenter] removeObserver:myView]

and it will remove observers for all notifications you subscribed

like image 23
storoj Avatar answered Oct 07 '22 19:10

storoj