开发者

How should I unregister for KVO on self?

I'm trying to use KVO to observe properties on a UIView subclass in order to trigger drawing by calling drawRect:. In my initWithFrame:, I have this:

...
self.observedKeysThatTriggerRedraw = [NSArray arrayWithObjects:@"name", nil];
for (NSString *aKey in self.observedKeysThatTriggerRedraw) {
    [self observeValueForKeyPath:aKey ofObject:self change:nil context:redrawContextString];
}
...

(redrawContextString is a constant NSString unique to this class)

The KVO notifications are firing as they should, which is triggering the redraw correctly. The problem is unregistering KVO. If I don't unregister, everything runs fine, but I get an exception if I put this at the top of my dealloc:

for (NSString *aKey in self.observedKeysThatTriggerRedraw) {
    [self removeObserver:self forKeyPath:aKey];
}

self.name = nil;
...
[super dealloc];

I get this message in the console and a crash when it gets to the removeObserver:forKeyPath::

CoreAnimation: ignoring exception: Cannot remove an observer <MyView开发者_StackOverflow社区Class 0x5b47210> for the key path "name" from <MyViewClass 0x5b47210> because it is not registered as an observer

Is there some trick to unregistering KVO when you are observing self? Are my observers being unregistered for me be the time dealloc is called? I've read in a bunch of places that you shouldn't unregister for KVO in dealloc, but I'm not sure where else I can do it when observing self.


You haven't actually registered the view as an observer with addObserver:forKeypath:options:context:. Either you should register self as an observer or (if you don't use KVO in a standard way, manually sending observeValueForKeyPath...), you should not try to unregister self as an observer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜