Is there a way to observe changes in derived properties? For example, I want to know when a CALayer has been added as a sublayer so that I can adjust its geometry relative to its (new) parent.
So, I have a subclassed CALayer, say CustomLayer, and I figured I could register an observer for the property in init:
[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]
and implement observeValueForKeyPath:ofObject:change:context
. Nothing ever happens because, presumably, superlayer is a derived property (the attr dictionary stores an opaque ID for the parent). Similarly, I can't subclass setSuperlayer:
because it is never called. In fact, as far as I can tell there are no instance methods called or public properties set on the sublayer when a parent does [self addSublayer:aCustomLayer]
.
Then I thought, OK, I'll subclass addSublayer like this:
- (void)addSublayer:(CALayer *)aLayer {
[aLayer willChangeValueForKey:@"superlayer"];
[super addSublayer:aLayer];
[aLayer didChangeValueForKey:@"superlayer"];
}
but still nothing! (Perhaps it's a clue that when I make a simple standalone test class and use the will[did]ChangeValueForKey:
then it works.) This is maybe a more general Cocoa KVO question. What should I be doing? Thanks in advance!