开发者

will any change to the member of class observed set off the observer to the member?

开发者 https://www.devze.com 2023-03-20 18:48 出处:网络
Let me make a example to show this: I have a class ClassA, it contains a public member memberA. it also contains a public method methodA, which will change the value of memberA.

Let me make a example to show this:

I have a class ClassA, it contains a public member memberA. it also contains a public method methodA, which will change the value of memberA.

now I开发者_JAVA技巧 have a instant of ClassA:

instantA

then I call this:

[instantA addObserver:anObserver forKeyPath:@"memberA" options:NSKeyValueObservingOptionNew context:NULL];

why this will touch off observer:

instantA.memberA = xxxxx;

but this won't:

[instantA methodA];


This is because the synthesized methods generated by the compiler for your properties are KVO compliant, but your method which makes manual changes probably isn't.

I'm guessing that in your method you are altering the iVar directly, rather than through the property?

For instance, are you doing this ...

- (void)methodA
{
    memberA = someValue;
}

or are you doing this ...

- (void)methodA
{
    self.memberA = someValue;
}

The latter will trigger the observer, the former won't. You can make the former trigger the observer by making it KVO compliant ...

- (void)methodA
{
    [self willChangeValueForKey:@"memberA"];
    memberA = someValue;
    [self didChangeValueForKey:@"memberA"];
}

See Apple's official docs here for more information on KVO compliance.

0

精彩评论

暂无评论...
验证码 换一张
取 消