Re: KVC and KVO for arrays
Re: KVC and KVO for arrays
- Subject: Re: KVC and KVO for arrays
- From: Adam P Jenkins <email@hidden>
- Date: Wed, 13 Feb 2008 11:51:05 -0500
On Feb 13, 2008, at 10:34 AM, mmalc crawford wrote:
On Feb 13, 2008, at 6:37 AM, Adam P Jenkins wrote:
Ah, you're correct. But my basic point still is correct, that you
do not need to subclass NSMutableArray or implement indexed
accessors yourself. You can just use the mutableArray* and
mutableSet* methods to have Cocoa do the work for you.
Again no. In the typical case, you *should* implement the indexed
accessors, otherwise you end up replacing the whole array/set each
time you make a change, which is extremely inefficient.
Thanks. You're correct, depending on how you write your entity
class. If your entity class does NOT provide indexed accessor methods
for an attribute, but DOES provide a set<Key> method for the array
attribute, then the array proxy returned by mutableArrayValueForKey
does behave the way you said, replacing the whole array any time an
element is changed.
However if your entity class doesn't provide a set<Key> method, but
DOES provide an instance variable named <key> whose value is an
NSMutableArray, then the proxy returned by mutableArrayValueForKey
will forward array modification messages directly to the underlying
NSMutableArray, while also sending the appropriate key/value observing
notifications. See the documentation for the mutableArrayValueForKey:
method of NSKeyValueCoding for details.
So basically, an easy way to get the effect of having indexed accessor
methods without having to write them is as follows:
@interface Palette : NSObject
{
NSMutableArray *colors;
}
// don't define a colors property or setColors: method
// returns a KVO compliant colors array
- (NSMutableArray*)kvoColors;
@end
@implementation Palette
- (NSMutableArray*)kvoColors
{
return [self mutableArrayValueForKey:@"colors"];
}
@end
Now, I can write
[[palette kvoColors] addObject:[NSColor whiteColor]];
and observers of palette will be duly notified.
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden