In Cocoa KVO, why doesn't a change on a NSMutableArray proxy notify observers?

前端 未结 1 1431
傲寒
傲寒 2021-01-05 12:31

I\'m implementing a DocumentsManager class in iOS, and I want to make a to-many property called documents to be KVO compliant. It seems to mostly w

相关标签:
1条回答
  • 2021-01-05 13:09

    It turns out that mutableArrayValueForKey: does not always return a notifying array. It only does so when observers have already been registered on the observed object!

    So swapping my first two lines fixes the problem:

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

    Can't help thinking how much time we'd save if we could read the source code of those methods…

    0 讨论(0)
提交回复
热议问题