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

标签 ios objective-c

我在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/

相关文章:

ios - 通知 UITableView dataSource 的变化

objective-c - NSKeyValueCoding中的IOS 13和Xcode 11崩溃

iphone - 为什么 Reachability 示例应用程序会在此处停止?

ios - 将参数传递给选择器操作

ios - UICollectionView 子类在多个 viewControllers 中重用

ios - UITableView 单元格计数不足

ios - UILabel 不会显示在多行中

ios - UICollectionView 始终在当前之前显示上一个选择

iphone - 鸽笼问题: Placing different types of UIImages into UIImageViews

ios - 从选项卡栏项目按执行模态和推送 Segue