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...]
?
Best Answer
No.
No. Implement the array accessors. When you call these, KVO will post the appropriate notifications automatically. So all you have to do is:
and the Right Thing will happen automatically.
For convenience, you can write an
addTheArrayObject:
accessor. This accessor would call one of the real array accessors described above:(You can and should fill in the proper class for the objects in the array, in place of
NSObject
.)Then, instead of
[myObject insertObject:…]
, you write[myObject addTheArrayObject:newObject]
.Sadly,
add<Key>Object:
and its counterpartremove<Key>Object:
are, last I checked, only recognized by KVO for set (as in NSSet) properties, not array properties, so you don't get free KVO notifications with them unless you implement them on top of accessors it does recognize. I filed a bug about this: x-radar://problem/6407437I have a list of all the accessor selector formats on my blog.