Key-Value-Observing and Collections
Chris Hanson
cmh at mac.com
Sun Oct 28 16:12:53 PDT 2007
On Oct 25, 2007, at 8:01 AM, Philip Mötteli wrote:
> Am 25.10.2007 um 16:47 schrieb Christiaan Hofman:
>
>> You should avoid that, in particular for collection keys (for those
>> there are other variants that allow you to pass precisely what has
>> changed). A much better and easier solution is to follow the docs:
>> use KVC compliant array accessors, like
>> insertObject:inGradesAtIndex:, which automatically send the correct
>> notifications.
>
> And how do I register as an observer?
>
> [theCollection addObserver:anObserver forKeyPath:???? options:0
> context:NULL];
>
> What do I have to use as the key(path)?
You don't. The point of key-value observing is that you're observing
a *property* of an object, not an object itself. In this case, you
would say
[objectWithTheCollectionProperty addObserver:anObserver
forKeyPath:@"theCollection"
options:options
context:context];
and whenever the property *represented by* the key "theCollection" is
mutated -- via the mutator methods that Christiaan Hoffman mentioned,
or via a proxy object returned by [objectWithTheCollectionProxy
mutableArrayValueForKey:@"theCollection"] -- you will receive a KVO
notification.
Note too that you probably shouldn't pass NULL for the context. The
context helps distinguish whether your -
observeValueForKeyPath:ofObject:change:context: callback is being
invoked on behalf of your observance or on behalf of some completely
unrelated observance. (This is particularly important when
implementing views that use KVO to handle bindings.) Typical practice
is to declare a C or NSString constant in your code and to pass *that*
as the context, and then do a pointer-equality check against it
(rather than an -isEqual: check, since you can't be guaranteed that an
arbitrary context you're passed is an object).
-- Chris
More information about the MacOSX-dev
mailing list