Question

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
Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top