使用KVO更改属性时发送通知 [英] Send Notification When a Property is Changed Using KVO
本文介绍了使用KVO更改属性时发送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的课程中有一个名为 myName
的属性,例如:
I had a property named myName
in my class, like:
@property (nonatomic, strong) NSString *myName;
我需要在 myName
属性值已更改。
I need to send a notification when the myName
property's value is changed.
现在我正在做类似的事情:
Now I'm doing something like:
- (void)setMyName:(NSString *)name
{
_myName = name;
[[NSNotificationCenter defaultCenter] postNotificationName:CHANGE_NOTIFICATION object:nil];
}
我知道有类似 键值观察 。但我不知道如何实现它,我阅读了整个文档,但无法理解。
I know there is something like Key-Value Observing in iOS. But I don't know how to implement it, I read the entire document, but couldn't get a good understanding.
请帮助我理解如何实现相同而不使用自定义setter。
Please help me to understand how to implement the same without using custom setter.
推荐答案
试试这个:
MyClass *var = [MyClass new];
[var addObserver:self forKeyPath:@"myName" options:NSKeyValueChangeOldKey context:nil];
并实施
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
}
当myName属性发生变化时,将随时调用此方法
this method will be called anytime when myName property changes
这篇关于使用KVO更改属性时发送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文