Observe the Count property of an NSMutableArray

I would like to observe the count property of an NSMutableArray object. I could directly observe the array for changes whenever an object was added or deleted using Indexed Assistants Array for relationships with many. However, I would just like to observe the count property instead, so when I use my observValueForKeyPath method, the object passed to this parameter is the array object itself, and not the class containing the array.

My situation is this:

I have NSMutableArray * maps declared in my AppDelegate class as a property (and ivar).

In my view controller, I am trying to check the count property of this array:

[appDelegate.cards addObserver:self forKeyPath:@"count" options:0 context:NULL]; 

However, this causes my program to crash with the following error:

 [<__NSArrayM 0x4e17fd0 addObserver:forKeyPath:options:context] is not supported. Key path: count' 

I tried implementing accessors for a many-many relationship.

 - (void)addCardsObject:(Card *)anObject; - (void)removeCardsObject:(Card *)anObject; 

However, the program still crashes.

I have a few questions:

  • How can I observe the count property of this NSMutableArray?
  • Is the NSMutableArray counting point defined as a one-to-one relationship, or is it the whole object that matters when determining whether it is a to-many or to-one relationship (NSMutableArray is a collection object, so it is a -many relationship, EVEN, although I'm just looking to observe the count property, not the properties of the objects in the collection).

Thanks in advance.

+4
source share
2 answers

NSArray itself does not support KVO, period. This is the controller in front of the array that you need to watch. For example, if you have an NSArrayController, you can set an observer for arrangedObjects.count .

+4
source

It is sad to know that NSarry, NSMutableArray do not support KVO. And I came across this when I wanted to use jet cocoa to observe the selection.

But, fortunately, the UIViewController meets the requirements of KVO.

 //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); }]; 
+1
source

All Articles