Re: Limited-access, KVO-compliant mutable array?
Re: Limited-access, KVO-compliant mutable array?
- Subject: Re: Limited-access, KVO-compliant mutable array?
- From: Quincey Morris <email@hidden>
- Date: Wed, 11 Jul 2012 00:24:42 -0700
On Jul 10, 2012, at 23:51 , Rick Mann wrote:
> It still bugs me, in the sense that publishing an NSArray* property seems to create a (conceptual) contract that while the property may change, that is, a different NSArray may get assigned to it, the contents of a given NSArray won't change. From what you've both said, this is clearly not the case. But it just smells a little funny.
No, your thinking is incorrect, in the sense that you're somewhat confusing the backing storage (i.e. instance variable and hence array pointer value) with the property value. It's perfectly fine, for example, for a class to implement an indexed to-many property like this (ignoring the proxy/mutability issues we were discussing before):
@implementation MyClass {
NSMutableArray* _arrayIvar;
}
- (NSArray*) myProperty {
return _arrayIvar;
}
- (void) setMyProperty: (NSArray*) newObjects {
[_arrayIvar removeAllObjects];
[_arrayIvar addObjectsFromArray: newObjects];
}
In that case, the returned array pointer is always the same. (The above code is KVO-compliant, BTW.)
Because it's a to-many property, there's no API promise regarding the pointer value returned by the getter. It just has to be a NSArray-like object that provides access to the objects "in" the relationship. There's also no inherent API promise saying whether the returned NSArray is a snapshot at a moment in time, or an object that reflects the current contents. If it matters, you have to settle the behavior by what you're returning. (In the above example, the difference would be exemplified by returning '[_arrayIvar copy]' vs. just '_arrayIvar'.)
> One last question: What if the underlying data structure isn't an array at all, but rather a dictionary? It's not possible to insert into it at a particular index. Although that wouldn't prevent me from implementing the methods, it seems it would break, because the OS (and clients) would assume remove and insert are paired, and guaranteed to work on the same index (that is, insert followed by remove should result in an unchanged array).
One way is to create a supplementary array data structure that lists the dictionary key values in the order that's correct for the array indexes. You maintain both data structures in your custom insert/remove/replace KVC accessors, as well as in methods that insert/remove dictionary entries for other reasons.
_______________________________________________
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