Key-Value-Observing a to-many relationship in Cocoa

后端 未结 3 901
萌比男神i
萌比男神i 2020-12-02 17:49

I am trying to get key-value-observing to work for an NSMutableArray. Below is the .h file for MyObservee, the observed class:

@interface MyObservee : NSObje         


        
3条回答
  •  -上瘾入骨i
    2020-12-02 18:15

    Why are you passing your private array to another object? It's not so private when you let other objects handle it.

    As s-bug said, you should implement the accessors and use mutableArrayValueForKey: to mutate the property. I add that you should not be exposing that private array at all—your someArray method should return an immutable copy of the array.

    Furthermore, I call your attention to Jason Coco's comment on s-bug's answer. To paraphrase him, you should probably use an NSArrayController as an additional step of separation between myObservee and myObserver. This is a very good suggestion, and if you don't have a specific reason to directly observe the property, you should take it. (Among the benefits is that you can then use Bindings to connect views to the new array controller.)

提交回复
热议问题