gpt4 book ai didi

ios - 如何制作一种检测变量是否更改的方法?

转载 作者:行者123 更新时间:2023-12-01 17:52:07 24 4
gpt4 key购买 nike

我在h文件中声明了@property (strong, nonatomic) NSString *data;,然后将另一个类的NSString传递给“数据”。我想检测“数据”是否已更新,所以我尝试了下面的代码,但它不起作用。

-(void)didChangeValueForKey:(NSString *)key {  

[super didChangeValueForKey:key];
if ( [key isEqualToString:@"data"] ) {
// do something
}
}

有人知道如何解决吗?

谢谢你,抱歉我的英语。

最佳答案

为此,可以使用键值观察

假设您有一个带有属性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

关于ios - 如何制作一种检测变量是否更改的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26583506/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com