2
votes

Suppose I have a class like this:

@interface MyClass : NSObject

@property (nonatomic, strong, getter=theDataGetter) NSMutableArray* theData; 

@end

@implementation MyClass
-(NSMutableArray *)theDataGetter
{
    return [self mutableArrayValueForKeyPath:@"theData"];
}
@end

here, because of kvo complience of the theData property (other kvo complience methods are skipped) and through mutableArrayValueForKeyPath i can observe insert,update,remove operations above the theData property. Now suppose that this array containing mutable dictionaries.

self.obj = [[MyClass alloc] init];
_obj.theData = [[NSMutableArray alloc] initWithObjects:
                   [NSMutableDictionary dictionaryWithObjectsAndKeys:@"The one with glasses.",@"description",@"Manny",@"name", nil],
                   [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Looks a little like Governor Dewey.",@"description",@"Moe",@"name", nil],
                   [NSMutableDictionary dictionaryWithObjectsAndKeys:@"The one without a mustache.",@"description",@"Jack",@"name", nil],
                   nil];

Now my question is how to observe changes to the value of the "description" key of any dictionary in the theData array. Suppose i want to observe the change of first object's description key's value to something different than holding now.

1

1 Answers

2
votes

If you want to observe the description property of any the objects of the array theData, the only way to go is to attach an observer to it directly.

[_obj.theData[0] addObserver:<observing object>
             forKeyPath:@"description"
                 options:(NSKeyValueObservingOptionNew |
                            NSKeyValueObservingOptionOld)
                    context:NULL];

This will observe changes to the first object.