Send Notification When a Property is Changed Using KVO

﹥>﹥吖頭↗ 提交于 2019-12-03 23:27:47
alex

Try this:

MyClass *var = [MyClass new];
[var addObserver:self forKeyPath:@"myName" options:NSKeyValueChangeOldKey context:nil];

and implement

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

}

this method will be called anytime when myName property changes

In - (void)setMyName:(NSString *)name do this instead

[self willChangeValueForKey:@"myName"];
_myName = name;
[self didChangeValueForKey:@"myName"];

//this generates the KVO's

And where you want to listen (the viewController), there in viewDidLoad add this line:

[w addObserver:self forKeyPath:@"myName" options:NSKeyValueObservingOptionNew context:nil];

//By doing this, you register the viewController for listening to KVO.

and also implement this method:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([[change objectForKey:NSKeyValueChangeNewKey] isEqual:[NSNull null]]) {
        return;
    } else {
        //read the change dictionary, and have fun :)
    }
}

//this method is invoked, whenever the property's value is changed.

To do this without the customer setter, just synthesize the property setter. This will create all the supporting calls to willChangeValueForKey / didChangeValueForKey.

@synthesize myName;

Then set property values with dot-syntax:

self.myName = @"Inigo Montoya"

Then the observers will receive the KVO notification automatically.

(You will need to remove the observer before you release the observed object.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!