开发者

iPhone - testing if a notification exists

At some point in a code one may add something like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doSomething) name:@"Hello" object:nil];   

How do I test if this notification is alrea开发者_高级运维dy active on the queue or has been removed, to prevent adding a duplicate?

thanks.


If you mean "testing for whether you've already registered as an observer for the notification", I don't think there's an easy way apart from posting the notification and seeing you get a callback (with possibly disastrous effects).

If there's a danger of a double-add, I usually use [[NSNotificationCenter defaultCenter] removeObserver:self name:foo object:bar] before the add.

Registering for notifications does not happen on a queue.


Remove observer before adding it:

How to avoid adding multiple NSNotification observer?

For unit testing you should mock NSNotificationCenter as it is dependency.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜