Jim Hubbard
Jim Hubbard

Reputation: 117

Observe Count Property of NSMutableArray Object

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:

  1. How would I be able to observe the count property of this NSMutableArray?
  2. 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.

Upvotes: 4

Views: 3901

Answers (2)

geekay
geekay

Reputation: 1673

Thats sad to know that NSarry, NSMutableArray do not support KVO. And I faced this when I wanted to use reactive cocoa to observe selection.

But thankfully, UIViewController is KVO compliant.

//create a readonly property selectionCount
@property (nonatomic, readonly)NSInteger selectionCount;
...

//Implement the getter method
-(NSInteger)selectionCount{
    return self.arrSelection.count;
}
...

RAC(self.btnConfirm, enabled) = [RACSignal combineLatest:@[RACAbleWithStart(self.selectionCount)] reduce:^(NSNumber *count){
        return @([count integerValue] > 0);
    }];

Upvotes: 1

Chuck
Chuck

Reputation: 237060

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.

Upvotes: 4

Related Questions