2

In the reference I see that registering an observer to notifications is possible with a null observer pointer. However, both remove methods require a valid pointer value that is not NULL. How do I overcome that when registration is done without one?

I also noticed in this answer example CFNotificationCenter usage examples? removing is done with NULL, but again, according to the reference - that is wrong .

So, what is the right way to remove registration done with NULL observer? Are they not supposed to be removed (they are just left there till memory is cleared due to application exit??)???

Any explanation is much appreciated!

Community
  • 1
  • 1
NightRider
  • 145
  • 1
  • 10

1 Answers1

4

There's no real penalty to sending an observer (which is a void *, and not interpreted by the system at all). The preferred use case is that if you are going to remove the observer, you should send an observer to both the initial CFNotificationCenterAddObserver call and the subsequent CFNotificationCenterRemoveObserver.

By example, it appears that passing NULL to both Add and Remove actually works, but as you point out it breaks the API contract to do so, therefore I wouldn't suggest using it in shipping code.

The observer itself is often just a string pointer and as long as you pass in the same pointer, you should be fine.

char *myObserver="anObserver";

CFNotificationCenterAddObserver ( notificationCenter, (void*)myObserver, myCallback, NULL, NULL, CFNotificationSuspensionBehaviorDrop);

and later:

CFNotificationCenterRemoveObserver ( notificationCenter, (void*)myObserver, NULL, NULL);  

Make sure you use the same string pointer, not just the same string, as Foundation is only checking for the equality of the void*, it knows nothing about the contents.

By way of further explanation, the reason for this pattern is so that you can use a single callback to handle multiple observers.

gaige
  • 17,263
  • 6
  • 57
  • 68
  • thanks for your answer. However, I still fail to grasp the logic behind the setting of a null observer that cannot be removed. I have a code written by another developer that registers null observers. I am unable to add an assigned one, and now theres no place where the notifications are removed due to this... – NightRider Apr 21 '13 at 07:28
  • I'm not sure what's difficult to understand here. Registering with a NULL observer basically makes it such that you can't remove it until the application quits. Although NULL is accepted, it is not advised. What do you mean by "I am unable to add an assigned one"? – gaige Apr 21 '13 at 10:58
  • I completely understand it, apart for apple's logic behind it. And by being unable to add an assigned one, I mean that it's in a part of the code I cannot change. As you say - the notifications are left there until the application exits. Thanks again, I'll accept your answer :) – NightRider Apr 22 '13 at 06:09