如何发布关于bool状态的NSNotificationCenter?

Sno*_*man 5 iphone objective-c ios

我正试图通过使用通知.在我的视图控制器类中,我有一个bool isFullScreen.当这个bool的值发生变化时,我希望将通知发送给所有观察类.我不太确定如何做到这一点,因为BOOL不是一个对象.我怎么做到这一点?

ban*_*isa 10

[[NSNotificationCenter defaultCenter] postNotificationName:YourNotificationName object:[NSNumber numberWithBool:isFullScreen]]; //YourNotificationName is a string constant
Run Code Online (Sandbox Code Playgroud)

KVO示例:

如果你是用KVO做的话,那将是类似下面的......:

[self addObserver:self forKeyPath:@"isFullScreen" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString: @"isFullScreen"]) {
        BOOL newValue = [[change objectForKey:NSKeyValueChangeNewKey] boolValue];
    }
}

//and in dealloc
[self removeObserver:self forKeyPath:@"isFullScreen" ];
Run Code Online (Sandbox Code Playgroud)


ber*_*ium 5

只需BOOL包装在 NSNumber 中:

[NSNumber numberWithBool:myBool]
Run Code Online (Sandbox Code Playgroud)