CFNotificationCenterRemoveObserver观察者 [英] CFNotificationCenterRemoveObserver observer

查看:250
本文介绍了CFNotificationCenterRemoveObserver观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考我看到使用空的观察者指针可以向观察者注册观察者.但是,这两种remove方法都需要一个有效的指针值,该值不能为NULL.如果没有一个人就完成注册,我该如何克服呢?

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?

在此答案示例中,我还注意到 CFNotificationCenter的使用示例?删除是使用NULL完成的,但还是根据参考-这是错误的.

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

那么,删除使用NULL观察器完成的注册的正确方法是什么?

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

任何解释都非常感谢!

推荐答案

发送观察者(这是一个void *,并且完全不被系统解释)并没有真正的惩罚.首选用例是,如果要删除观察者,则应同时向初始CFNotificationCenterAddObserver调用和后续的CFNotificationCenterRemoveObserver发送observer.

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.

通过示例,看来将NULL传递给Add和Remove确实有效,但是正如您所指出的那样,这样做违反了API合同,因此,我不建议在运输代码中使用它.

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.

observer本身通常只是一个字符串指针,只要您传递相同的指针,就可以了.

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

及更高版本:

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

请确保使用相同字符串指针,而不仅仅是同一字符串,因为Foundation仅检查void*的相等性,因此对内容一无所知.

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.

这篇关于CFNotificationCenterRemoveObserver观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆