I would like to observe the count property of an NSMutableArray object. I was able to directly observe the array for changes whenever an object was added or removed by utilizing the Indexed Array Accessors for a to-many relationship. However, I would like to simply observe the count property instead, so that when I use my observeValueForKeyPath method, the object being passed into the parameter is the array object itself, rather than the class holding the array.
My situation is as follows:
I have an NSMutableArray *cards declared in my AppDelegate class as a property (and ivar).
From my viewcontroller, I try observing the count property of this array:
[appDelegate.cards addObserver:self forKeyPath:@"count" options:0 context:NULL];
However, this crashes my program with the following error:
[<__NSArrayM 0x4e17fd0 addObserver:forKeyPath:options:context] is not supported. Key path: count'
I’ve tried implementing the accessors for a to-many relationship
- (void)addCardsObject:(Card *)anObject;
- (void)removeCardsObject:(Card *)anObject;
However, the program still crashes.
I have a few questions:
- How would I be able to observe the count property of this NSMutableArray?
- Is the count propety of the NSMutableArray defined as a to-one relationship, or is it the entire object that matters when determining whether it’s a to-many or to-one relationship (NSMutableArray is a collection object, therefore it’s a to-many relationship, EVEN though I’m merely looking to observe the count property, and not properties of objects in the collection).
Thanks in advance.
NSArray itself just doesn’t support KVO, period. It’s the controller in front of the array that you need to observe. For example, if you have an NSArrayController, you can set an observer for
arrangedObjects.count.