Re: Dependent values that are not iVars
Re: Dependent values that are not iVars
- Subject: Re: Dependent values that are not iVars
- From: Paul Bruneau <email@hidden>
- Date: Fri, 18 Dec 2009 14:18:10 -0500
On Dec 18, 2009, at 2:08 PM, Quincey Morris wrote:
This is a situation where you use willChangeValueForKey:/
didChangeValueForKey:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:
(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:kOverallWidth]) {
[self willChangeValueForKey:@"overallWidth"];
NSLog(@"got notification that overallwidth changed: %@", object);
[self didChangeValueForKey:@"overallWidth"];
}
}
Ahh, of course, thank you Quincey!
A couple of things I notice:
1. You have 2 identically named properties ("overallWidth") in
related objects. My experience has been that if there's ever
anything wrong with (say) your bindings, it gets incredibly
confusing working out from logged error messages *which* property
has the problem. You can save yourself some grief by renaming (say)
your dependent property to (say) "overallWidthSubtotal".
OK I see what you are saying. I will rename one or both of them.
2. Your observer method is stripped down, right? You are really
using a unique value for the context parameter, right? It's not
really safe to just not care.
No, I'm not using context. My feeling was that since I am checking for
the keypath, that is all I needed to care about. Can you elaborate
about the unsafeness of that? Thank you.
3. Your dependent property is *also* dependent on the array itself.
You will also put the willChange/didChange invocations in the
place(s) where you add/remove/replace objects in the underlying
array, yes?
Yes, thanks for the note on that. I had already noticed that I needed
that for when objects in the collection get added or removed.
4. The use of willChange/didChange in the observer method causes a
nested KVO notification. (It triggers at the didChange invocation.)
In general, you have to be a little careful that your observer
method puts your object in an internally consistent state before
triggering the notification, and that you don't cause any infinite
notification loops. This is likely not a problem if this is all your
code, but it's something to keep in mind. (Actually, it's a
potential issue anywhere you trigger a nested notification, such as
when you set a property inside a different property setter method.)
I think I have a vague understanding of what you are saying. I *think*
I'm OK in this area but I will watch out for problems.
Thanks again!
_______________________________________________
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