Cocoa 中的关键值观察,内省更改属性
我正在使用 NSObject 方法对布尔属性进行键值观察:
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
此键路径的值中最有趣的部分是一个 BOOL,它不断在 YES/NO 之间翻转。 我从更改字典中得到的最多的是 kind = 1。有没有办法不探测我正在观察的对象来查看实际的更改值是什么?
谢谢。
I'm using key value observing on a boolean property an NSObject method:
-(void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
The most interesting part of the value for this key path is a BOOL which is constantly flipping between YES/NO. The most I get out of the change dictionary is kind = 1. Is there anyway without probing the object I'm observing to see what the actual change value is?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您指定 NSKeyValueObservingOptionNew:
…然后,在您的观察者方法中:
理想情况下,您会在调用
- 之前检查 value 是否为
,但为了清楚起见,此处省略了该值。nil
(好吧,它可能会发生) boolValueFirstly, you specify NSKeyValueObservingOptionNew:
…then, in your observer method:
Ideally you'd check whether value was
nil
(well, it might happen) before calling-boolValue
, but that was omitted for clarity here.正如 Jim Dovey 所说,除了更改字典不会带来 nil,而是 null 值,因此这
将导致类似的结果:
如前所述,对 null 值调用 boolValue 将导致错误
为了避免这种情况,必须检查 [NSNull null] 而不是 nil,如下所示
:
As Jim Dovey says, except that the change dictionary does not bring nil, but null values, so that
will result in something like:
As mentioned, calling boolValue on a null value will result in an error
To avoid this, one has to check not for nil but for [NSNull null], like so:
or