Observe value changes of NSDictionary inside NSArray

别等时光非礼了梦想. 提交于 2019-12-08 07:22:40

问题


here's my 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";
    }
)

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

carType is a NSArray property of context

- (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

回答1:


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:

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).

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).



来源:https://stackoverflow.com/questions/21821093/observe-value-changes-of-nsdictionary-inside-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!