objective c - Is it safe to observe a keyPath when an object along the path may change? -
is safe implement kvo such:
[self addobserver:self forkeypath:@"restaurant.oldestorder.patron.frustrationlevel" options:0 context:nil];
…when know oldestorder
might change or become nil, , previous oldestorders
might become deallocated?
executive summary:
you never need add observer twice same key because keys in middle changed, nskeyvalueobserving
you.
as long -oldestorder
method doesn't return dangling pointer, nothing should break.
the way kvo works when add observer, observer added list on observed object, in form of nsobservationinfo
object. easy. nsobservationinfo
object raw key (not path), object watch, observer call, pointer context passed, , other bookkeeping stuff.
when observe path of keys, observer relationships observed through respective nsobservationinfo
objects, held in list on called object, if whole path property of object called -addobserver
on.
in example self
observes restaurant
, addobserver:
method creates nsobservationinfo
objects in background added observers each respective object down path, , these added self's list of observers.
when observe @"a.b.c.d"
of object, creates 4 nsobservationinfo
objects, 1 each key relation, , these added each key on path observer, nsobservationinfo
object watching a
of called, 1 watching b
of a
, 1 watching c
of b
, etc. when 1 of these nsobservationinfo objects observes change, passes along original -addobserver
caller change entire keypath.
(this implementation detail should explanation.)
when object in middle of path nil'd or removed, -willchangevalueforkey
notices , dutifully removes nsobservationinfo
objects observers, along path after nil'd object. these nsobservationinfo
objects still exist though, , still know keys want see, , when -didchangevalueforkey
called, @ new value key , if has key names matching ones it's chain of nsobservationinfo
objects looking for, attach them new observers.
so, when element along path @"restaurant.oldestorder.patron.frustrationlevel"
changes, change notification, nskeyvalueobserving
machinery attempt reestablish relationship key @ end of path after change, , subsequent change.
here's cocoatron's implementation of this, can see how works yourself.
Comments
Post a Comment