关于简单类型的KVO(IOS 5)(非NSObject)

Tor*_*ben 3 key-value-observing ios

我遇到了使IOS(objective-c)KVO为int类型的键工作的问题.

我的类声明了一个int类型的属性sampleValue.由于int没有自动实现KVO功能,所以我已经自动覆盖了该方法,因此将NototOotifiesObserversforKey覆盖为:

+ (BOOL)automaticallyNotifiesObserversForKey:(NSString *)theKey {

    BOOL automatic = NO;
    if ([theKey isEqualToString:@"sampleValue"]) {
        automatic = NO;
    } else {
        automatic=[super automaticallyNotifiesObserversForKey:theKey];
    }
    return automatic;
}
Run Code Online (Sandbox Code Playgroud)

正如我所期望的那样调用该方法.我也为sampleValue属性实现了一个setter方法,如下所示:

- (void) setSampleValue:(int)newSampleValue
{
    [self willChangeValueForKey:@"sampleValue"];
    sampleValue = newSampleValue;
    [self didChangeValueForKey:@"sampleValue"];
}
Run Code Online (Sandbox Code Playgroud)

在观察者类中设置观察者就像这样(dc是被观察对象的实例):

[dc addObserver:self forKeyPath:@"sampleValue" options:NSKeyValueObservingOptionNew context:NULL];
Run Code Online (Sandbox Code Playgroud)

但是,更新sampleValue时,不会向我的observer对象发送通知.更新NSDate类型的另一个属性非常好.

任何人都可以帮助我弄清楚我做错了什么或者我应该做些什么来使这项工作.

最好的问候Tomo

Cal*_*leb 7

也许我在你的问题中遗漏了一些东西,但你可以int像其他类型一样轻松地观察类型的属性而不做任何特殊的事情.

尝试删除你的+automaticallyNotifiesObserversForKey:覆盖和你的-setSampleValue:setter,只需合成访问者sampleValue:

@synthesize sampleValue;
Run Code Online (Sandbox Code Playgroud)

int是与key对应的值的类型@"sampleValue",但它不是被观察到的东西.被观察的对象是dc,并且当sampleValue属性被更改时它将负责发送适当的通知.