gpt4 book ai didi

objective-c - NSNotificationCenter - 使用多种方法观察通知名称

转载 作者:行者123 更新时间:2023-12-03 16:58:43 27 4
gpt4 key购买 nike

所以,我有一个对象,它有方法来切换监视某个通知名称,如下所示:

- (void)startWatchingForA
{
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleA:)
name: SomeNotificationName
object: nil];
}

- (void)stopWatchingForA
{
[[NSNotificationCenter defaultCenter] removeObserver: self
name: SomeNotificationName
object: nil];
}

效果很好。但是,我有另一种方法 handleB:,它需要响应相同的通知。

- (void)startWatchingForB
{
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleB:)
name: SomeNotificationName
object: nil];
}

- (void)stopWatchingForB
{
[[NSNotificationCenter defaultCenter] removeObserver: self
name: SomeNotificationName
object: nil];
}

问题是,如果调用 stopWatchingAstopWatchingB,对象将停止监视两者。有没有办法删除一个观察实例,而不删除另一个?

理想情况下,当我调用 stopWatchingForA 时,我希望不调用 handleA:,完全独立于 B

最佳答案

稍微重新设计一下怎么样?只有一种接收通知的方法,以及两个标志来指示您想用它做什么。

@implementation ThisObject
{
BOOL isWatchingForA;
BOOL isWatchingForB;
}

- (void) registerForNotifications {

[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(handleNotification:)
name: SomeNotificationName
object: nil];
}

- (void) deregisterForNotifications {
if( !isWatchingA && !isWatchingB ){
[[NSNotificationCenter defaultCenter] removeObserver: self
name: SomeNotificationName
object: nil];
}
}


- (void) startWatchingForA {
isWatchingForA = YES;
}
- (void) stopWatchingForA {
isWatchingForA = NO;
}

- (void) startWatchingForB {
isWatchingForB = YES;
}
- (void) stopWatchingForB {
isWatchingForB = NO;
}

- (void) handleNotification: (NSNotification *)note {

if( isWatchingForA ){
[self handleA:note];
}
if( isWatchingB ){
[self handleB:note];
}
}

//...

@end

关于objective-c - NSNotificationCenter - 使用多种方法观察通知名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9474572/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com