Re: Doesn't -willChangeValueForKey: copy the value before I change it?
Re: Doesn't -willChangeValueForKey: copy the value before I change it?
- Subject: Re: Doesn't -willChangeValueForKey: copy the value before I change it?
- From: David Spooner <email@hidden>
- Date: Sat, 15 Dec 2007 10:16:04 -0700
I believe -willChangeValueForKey: simply retains the result of -
valueForKey: when there are observers requesting the old value. If
you're signaling a change using -willChangeValueForKey:/-
didChangeValueForKey: then you should arrange that the object returned
by -valueForKey: is either immutable or a copy of your internal
mutable representation.
Implementing the following KVC compliance methods will ensure that -
valueForKey:@"stuffs" returns a set other than _stuffs
- (void) countOfStuffs;
- (NSEnumerator *) enumeratorOfStuffs;
- (id) memberOfStuffs:(id)aStuff;
You might also consider using the following more precise notification
for removal...
NSSet *removedObjects = [NSSet setWithObject:[_stuffs anyObject]];
[self willChangeValueForKey:@"stuffs"
withSetMutation:NSKeyValueMinusSetMutation usingObjects:removedObjects];
[_stuffs minusSet:removedObjects];
[self didChangeValueForKey:@"stuffs"
withSetMutation:NSKeyValueMinusSetMutation usingObjects:removedObjects];
Cheers,
dave
On 14-Dec-07, at 6:58 PM, Jerry Krinock wrote:
I've implemented a KVO-compliant NSMutableSet instance variable. It
has this little mutator:
- (void)deleteSomeStuff {
[self willChangeValueForKey:@"stuffs"] ;
#ifdef DO_IT_MY_WAY
[_stuffs removeObject:[_stuffs anyObject]] ;
#else
NSMutableSet* newStuffs = [_stuffs mutableCopy] ;
[_stuffs release] ;
[newStuffs removeObject:[newStuffs anyObject]] ;
_stuffs = newStuffs ;
#endif
[self didChangeValueForKey:@"stuffs"];
}
Either way, the observer gets notified, but if I DO_IT_MY_WAY, the
"old" value in the notification is wrong; it is the same as the
"new" value. My mental picture is that -willChangeValueForKey: is
invoked to copy the "old" value immediately before a change. But it
looks like maybe I'm wrong.
Can someone please explain, at a little higher level, what's wrong
with my picture?
Jerry
_______________________________________________
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