简体   繁体   English

观察者的整数属性

[英]Observer for an integer property

I got an an integer property, which value might change during run-time. 我有一个整数属性,该值可能会在运行时更改。 Therefore, I would like to register this property to an observer in order to receive a notification and call method, if this value has changed. 因此,如果此值已更改,我想将此属性注册给观察者,以便接收通知和调用方法。 I red already the Apple Documentation but as far as I understand this is just working for NSObjects and not for integers. 我已经使用了Apple文档,但据我了解,这仅适用于NSObjects ,不适用于整数。 In my .h I created @property int activePlayer; 在我的.h我创建了@property int activePlayer; .

This is what I am doing in my viewDidLoad 这就是我在viewDidLoad所做的

[self.activePlayer addObserver:playerChangedObserver
          forKeyPath:@"activePlayer"
             options:(NSKeyValueObservingOptionNew |
                      NSKeyValueObservingOptionOld)
             context:NULL];

Looking forward for some help. 期待获得帮助。 Thanks 谢谢

UPDATE 更新

Maybe you need some additional information. 也许您需要一些其他信息。 The .h and .m are implementing an UIViewController , in which I am using a flick gesture. .h.m正在实现UIViewController ,在其中我使用了轻拂手势。 If the gesture is weak, the int is 1, if it is a bit stronger it will change to 2 . 如果手势较弱,则int为1;如果手势稍强一些,则它将更改为2 In my project it makes sense to use this variable, so I can't remove it. 在我的项目中,使用此变量很有意义,因此无法删除它。

I changed the observer registration into: 我将观察员注册更改为:

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

The first self is the observed object, from which the property comes from. 第一个self是观察对象,属性来自该对象。 The key-path is the property and the second self I took, because it also should receive the message, if the key changes. 密钥路径是属性和我获取的第二个self ,因为如果密钥发生更改,它也应该接收消息。 Do I misunderstand something there? 我会误会那里的东西吗?

Have you actually tried this code? 您是否实际尝试过此代码? The introductory example for key-value observing is for an integer property. 键值观察的入门示例是整数属性。 It states further on that 它进一步指出

If the property is a scalar or a C structure, the value is wrapped in an NSValue object (as with key-value coding). 如果属性是标量或C结构,则将值包装在NSValue对象中(与键值编码一样)。

So, you'll need to unpack it before you can do anything with it, but it should work as is. 因此,您需要先打开包装,然后再对其进行任何处理,但它应该可以正常工作。

you should implement in your .m 你应该在你的.m中实现

observeValueForKeyPath:ofObject:change:context:

and you should use 你应该用

self.activePlayer = 1;

to set your 'activePlayer' property 设置您的“ activePlayer”属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM