KVO: unable to remove observer

My interface has an NSTextField that value bound to NSArrayController's selection.selectedType.title . All NSArrayController's objects are user objects, each of which has two methods:

 - (MYType *)selectedType; - (void)setSelectedType: (MYType *)type; 

do not have iVar selectedType . However, they have an iVar containing all MYType objects. The code comes down to the following:

 - (MYType *)selectedType { if (someIndex == 0) return [types objectAtIndex: 0]; else return [self typeWithIndex: someIndex]; } - (void)setSelectedType: (MYType *)type { someIndex = [type index]; } 

MYType objects got iVar NSString *title with the corresponding @property and synthesize .

Whenever I call setSelectedType: changes are immediately visible in the NSTextField , and everything seems to work, but I get a message with the message:

It is not possible to remove the NSArrayController 0x141160 observer for the path key "selectedType.title" from MYType 0x1a4830, most likely because the value for the "selectedType" key has changed without sending a corresponding KVO notification. Check the KVO correspondence of the MYType class.

I tried encapsulating the setSelectedType: method with willChangeValueForKey: and didChangeValueForKey: and then I got a log message, but another:

Cannot remove observer NSKeyValueObservance 0x1c7570 for key path "title" from MYType 0x1a4be0, because it is not registered as an observer.

+4
source share
2 answers

Use accessors first. Do not contact your ivars directly. You bypass KVO for someIndex because you directly modify ivar. Do not touch ivars directly if you do not need to.

You also need to tell KVO that selectedType depends on someIndex (and / or someStuff , this is not clear from your distilled code).

 + (NSSet *)keyPathsForValuesAffectingSelectedType { return [NSSet setWithObjects:@"someIndex", nil]; } 

This tells the KVO system that when someIndex changes someIndex it causes an implicit change in selectedType . See Register Dependent Keys .

+5
source

I encountered the same error, but for a different reason. Probably worth mentioning this in case anyone else closes here.

I am writing an application in Swift and I forgot the var prefix with dynamic

0
source

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


All Articles