我在h文件中声明@property (strong, nonatomic) NSString *data;
,并将NSString
从另一个类传递给"数据"。我想检测一下"数据"已更新,所以我尝试了下面的代码,但它没有工作。
-(void)didChangeValueForKey:(NSString *)key {
[super didChangeValueForKey:key];
if ( [key isEqualToString:@"data"] ) {
// do something
}
}
任何人都知道如何解决这个问题?
谢谢你,对不起我的英语。
答案 0 :(得分:4)
执行此操作的方法是使用键值观察。
假设你有一个带有myObject
属性的对象data
,那么你可以这样做......
[self.myObject addObserver:self forKeyPath:@"data" options:NSKeyValueObservingOptionNew context:nil];
然后你有方法......
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
// if you observer multiple properties then they will all fire this method
// so you need to determine that the right property is being observed
if (object == self.myObject
&& [keyPath isEqualToString:@"data"]) {
// if you are here then you know the object that changed is myObject
// and the property is the data property.
id theNewData = change[NSKeyValueChangeNewKey];
// this is the new state of the data
// you can also get the old state by using different options when adding the observer.
}
}
您可以阅读更多相关信息in the Apple documentation about KVO
答案 1 :(得分:0)
使用键值编码 - 这在UI更新中使用很多参考使用此link