10

How can I set KVO (key-value-observing) with an NSMutableArray?

I want to be notified when a change appears in the array. I never used KVO before with a collection like an array.

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Zingu
  • 103
  • 1
  • 4

2 Answers2

9

I think you'll be interested in the answers to this question.

The key is that you can't observe any properties on the array directly—the array is just storage—but you can observe the to-many relationship that's backed by that array (here I'm assuming your array is a property on an object somewhere).

If you don't want to use those special accessors all over the place, your code that owns the array can call

-willChange:valuesAtIndexes:forKey: and

-didChange:valuesAtIndexes:forKey:

as described in this answer.

And if you're on a Mac and not iOS, you should consider NSArrayController.

Bruno Bieri
  • 9,724
  • 11
  • 63
  • 92
Joe Osborn
  • 1,145
  • 7
  • 10
0

You can use KVOMutableArray. It is a subclass of NSMutableArray, and it supports KVO.

disclaimer: I am the author :)

Hai Feng Kao
  • 5,219
  • 2
  • 27
  • 38
  • Sorry, I don't really want to downvote—but I'm questioning the quality of the linked library. At best, it could be described as an observable container implementation. What it is not is **a KVO compliant NSMutableArray**. @JoeOsborn describes in the other answer this is a misunderstanding of the KVO concept: KVO needs an observable *key*, which can be used to form *key paths* through the object hierarchy. Cocoa has no way of addressing collection objects themselves using a key. – Nikolai Ruhe Nov 21 '16 at 13:21
  • @NikolaiRuhe Yes, it is an observable container implementation and the container happens to be a subclass of NSMutableArray. The original question asks for a way to monitor the changes of array. It indeed provides a way to do it. It does use a observable key, which is "observer.arr". I believe we are on the same page. – Hai Feng Kao Nov 21 '16 at 17:20