In Cocoa KVO, why changes to the NSMutableArray proxy do not notify observers?

I am implementing the DocumentsManager class on iOS, and I want the to-many property called documents to comply with KVO requirements. This basically works, and my KVO access methods and mutators are called. However, my concern is that any change made directly to the NSMutableArray proxy returned by calling mutableArrayValueForKey: in my instance does not notify observers.

So, this code notifies me about the insertion of @"aaa" , but not about @"bbb" , although both of them are actually inserted into visible ones in docsProxy . Is this expected behavior? If so, what is the advantage of using mutableArrayValueForKey: :?

 NSMutableArray *docsProxy = [[DocumentsManager instance] mutableArrayValueForKey:@"documents"]; [[DocumentsManager instance] addObserver:self forKeyPath:@"documents" options:NSKeyValueObservingOptionNew context:NULL]; [[DocumentsManager instance] insertObject:@"aaa" inDocumentsAtIndex:0]; // OK [docsProxy insertObject:@"bbb" atIndex:0]; // no notification! 
+6
source share
1 answer

It turns out that mutableArrayValueForKey: does not always return a notification array. This happens only when observers are already registered at the observed object!

Thus, replacing the first two lines fixes the problem:

 [[DocumentsManager instance] addObserver:self forKeyPath:@"documents" options:NSKeyValueObservingOptionNew context:NULL]; NSMutableArray *docsProxy = [[DocumentsManager instance] mutableArrayValueForKey:@"documents"]; 

It is impossible to think how much time we will save if we could read the source code of these methods ...

+5
source

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


All Articles