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

后端 未结 3 907
萌比男神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条回答
  •  生来不讨喜
    2020-12-02 18:23

    Unfortunately, The NSArray classes are note KVO compliant. They are KVC compliant, but you can't observe them directly like you're trying to do here. The easiest way to get this functionality would be to use an NSArrayController. The NSArray controller is KVO compliant and will alert you when items are added or removed. In your example, your observer would be notified if you actually changed the array itself. For instance, if you did something like this:

    [moe setSomeArray:[NSMutableArray array]];
    

    Which is probably not what you wanted at all :) Just as an aside, NSDictionary is actually KVO compliant so you could use that, if you chose. Or you could write a wrapper subclass of NSMutableArray that just creates a real mutable array as its backing store but just forwards on all messages to it except addObject and removeObject which you could override to trigger notifications.

提交回复
热议问题