Reputation: 117
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:
Thanks in advance.
Upvotes: 4
Views: 3901
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
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