Observing an NSMutableArray for insertion/removal
- by Adam Ernst
A class has a property (and instance var) of type NSMutableArray with synthesized accessors (via @property). If you observe this array using:
[myObj addObserver:self forKeyPath:@"theArray" options:0 context:NULL];
And then insert an object in the array like this:
[[myObj theArray] addObject:[NSString string]];
An observeValueForKeyPath... notification is not sent. However, the following does send the proper notification:
[[myObj mutableArrayValueForKey:@"theArray"] addObject:[NSString string]];
This is because mutableArrayValueForKey returns a proxy object that takes care of notifying observers.
But shouldn't the synthesized accessors automatically return such a proxy object? What's the proper way to work around this--should I write a custom accessor that just invokes [super mutableArrayValueForKey...]?