Re: KVO and Object Arrays
Re: KVO and Object Arrays
- Subject: Re: KVO and Object Arrays
- From: Jake Carter <email@hidden>
- Date: Sun, 20 Apr 2008 09:04:54 -0700
Murph,
Thanks for the info. This is a really great place for me to start.
:// Jake
On Apr 20, 2008, at 8:56 AM, Sean Murphy wrote:
On Apr 20, 2008, at 1:13 AM, Jake Carter wrote:
So the AppDelegate will contain an array of Foo object and each Foo
object will have an array of Bar objects. I want to be able to
observe the bars from the AppDelegate to see when new bars are
added or when a property changes in each bar object. I know I can
use addObserver:forKeyPath:options:context: and add it to each key
I want to observe, but is there a better way to do this? Maybe some
KVO magic way to watch a whole tree of objects and their properties?
Hey Jake,
Unfortunately, while KVO and bindings can often seem magical, the
need to observe changes to properties in an array brings you
slightly back to reality, requiring a bit more manual code to be
introduced.
In your case, registering AppDelegate as an observer of Foo's array
of Bar objects will allow it to receive notification only when
objects are added and removed from the Bar array. Changes to
specific attributes of your Bar objects, name and number, do not
trigger any notification.
The general approach is to register as an observer of the array
itself first, and when notified about the addition of objects,
register to observe specific properties in each of them. You should
also pay attention to objects removed from the array, and unregister
an an observer of their properties.
Malcolm Crawford has written some excellent documentation about this
topic at <http://homepage.mac.com/mmalc/CocoaExamples/
controllers.html> under the heading "Observing a collection is not
the same as observing the properties of the objects in a
collection." Also be sure to take a look at his "Graphics Bindings"
example, specifically the observeValueForKeyPath:... and
startObservingGraphics: method implementations in GraphicsView.m.
Having your model objects use keyPathsForValuesAffectingValueForKey:
(or setKeys:triggerChangeNotificationsForDependentKey: pre 10.5)
allows for an elegant way to perform this task, simplifying your
controller's registration and observation in cases where you
generally need to respond identically to a group of properties no
matter which specific one was modified.
Hope that helps,
-Murph.
_______________________________________________
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