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: Chris Hanson <email@hidden>
- Date: Sat, 15 Dec 2007 17:41:14 -0800
On Dec 14, 2007, at 5:58 PM, Jerry Krinock wrote:
I've implemented a KVO-compliant NSMutableSet instance variable. It
has this little mutator:
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?
I think it's your expectation that the old value is being copied
that's wrong. Key-Value Observing needs to work with an instance of
any subclass of NSObject, not just those that conform to <NSCopying>,
so it can only really retain.
Furthermore, whether you're implementing a to-many reference or
containment relationship, you'll want to post the appropriate mutable-
set KVO notifications rather than just generic KVO notifications.
This will allow the notification mechanism to be much more efficient.
You can also make this happen very easily by just implementing a
fuller suite of the mutable-set KVC cover methods in your class, *and
using them yourself*. It's a code smell to have -
{will,did}ChangeValueForKey: invocations in code that isn't a KVC
accessor/mutator for the key in question.
Thus your -deleteSomeStuff method should really look like this:
- (void)removeOneArbitraryStuff {
[self removeStuffsObject:[_stuffs anyObject]];
}
Your implementation of -removeStuffsObject: doesn't even need to
manually post KVO notifications. If you have automatic KVO
notification posting enabled for the "stuffs" key in your class (it's
on by default for NSObject subclasses, off by default for
NSManagedObject subclasses) then the fact that -removeStuffsObject: is
a mutable-set KVC mutator for the "stuffs" property will be sufficient
to cause proper notifications to be posted.
-- Chris
_______________________________________________
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