观察NSArray中NSDictionary的值变化 [英] Observe value changes of NSDictionary inside NSArray

查看:78
本文介绍了观察NSArray中NSDictionary的值变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的NSArray

carType (
        {
        isSelected = 0;
        kFieldName = "All types";
        kObjectValue = 0;
        kObjectValueText = All;
    },
        {
        isSelected = 0;
        kFieldName = "4 seats";
        kObjectValue = 4;
        kObjectValueText = "4 seats";
    },
        {
        isSelected = 1;
        kFieldName = "7 seats";
        kObjectValue = 7;
        kObjectValueText = "7 seats";
    }
)

如何观察isSelected字段的变化? 我在代码中使用了KVO,但是它不起作用.

how can I observe the change of isSelected field ? I used KVO in my code but it doesn't work.

carTypecontextNSArray属性

- (void)viewDidLoad
{
    [super viewDidLoad];
    [context addObserver:self forKeyPath:@"carType" options:NSKeyValueObservingOptionNew context:NULL];
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:@"carType"]) {
        NSLog(@"carType changed");
    }
}

//dealloc remove observer

推荐答案

要观察数组中每个字典在isSelected中的变化,您将必须以观察者的身份注册到数组中的每个字典.正如我在我的书中所说的:

To observe the change in isSelected for every dictionary in the array, you will have to register as an observer with every dictionary in the array. As I say in my book:

您可以使用NSArray的实例方法addObserver:toObjectsAtIndexes:forKeyPath:options:context:有效地做到这一点,但是如果数组本身是可变的,那么您还必须向该键注册该键,然后再添加到该数组中的任何新字典(然后取消注册)当从数组中删除字典时.

You can do that efficiently with NSArray’s instance method addObserver:toObjectsAtIndexes:forKeyPath:options:context:, but if the array itself is mutable then you’re also going to have to register for that key with any new dictionaries that are subsequently added to the array (and unregister when a dictionary is removed from the array).

最后一部分可能会令人生畏.在许多情况下,最好完全放弃,而只使用一个自定义类,该类在发生突变时会发出通知(而不是NSDictionary,而不是KVO).

That last part can get really daunting. Under many circumstances, it might be best to give up entirely and just use a custom class that emits a notification when it is mutated (instead of an NSDictionary, and instead of KVO).

这篇关于观察NSArray中NSDictionary的值变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆