How do I unregister for KVO?

I am trying to use KVO to observe properties in a subclass UIViewto invoke drawing by invoking drawRect:. In mine 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];
}
...

( redrawContextStringis a constant NSStringunique to this class)

KVO notifications start as they should, which correctly starts the redraw. The problem is to unregister the KVO. If I do not unregister, everything works fine, but I get an exception if I put this at the beginning of mine 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 crash when it falls into removeObserver:forKeyPath::

CoreAnimation: : < MyViewClass 0x5b47210 > "" < MyViewClass 0x5b47210 > ,

- KVO, self? , dealloc ? , KVO dealloc, , , self.

+3
1

addObserver:forKeypath:options:context:. , ( KVO , observeValueForKeyPath...), .

+1

Source: https://habr.com/ru/post/1789418/


All Articles