For my @property
s, I can make a setter to do some extra work when that property is modified, but with an NSMutableArray I often use methods such as [NSMutableArray replaceObjectAtIndex:(NSInteger) withObject:(id)];
to modify the array. How can I write a method that will be called when an object is replaced/inserted in the NSMutableArray?

- 1,333
- 12
- 24
-
possible duplicate of [Key Value Observing with an NSArray](http://stackoverflow.com/questions/3478451/key-value-observing-with-an-nsarray) – Andrew Miner Aug 01 '14 at 21:54
1 Answers
The best solution is to use the Key-Value Observing system to observe changes to the array. However, it's not exactly straight-forward to do this with an array.
Quoting from a similar question:
You can't call
-addObserver:forKeyPath:options:context:
directly on an NSArray... you want to call it on your [object] with [the property name] as the key.You're not done yet though. The normal automatic KVO notifications will only kick in if you call
-setPlayerNameArray:
, thereby replacing the entire array. If you want more granular notifications, then you need to use-willChange:valuesAtIndexes:forKey:
and-didChange:valuesAtIndexes:forKey:
whenever you insert, remove, or replace items in that array.This will send a notification whenever the contents of the array changes. Depending on the NSKeyValueObservingOptions you use when adding your observer, you can also get the incremental changes that are made—a cool feature, but you may not need it in this case.
Sort of making that work for you, it's not too difficult to make a new ObservableArray
class which uses an NSArray
internally, but publishes NSNotification
s whenever something is changed.

- 1
- 1

- 5,587
- 2
- 22
- 26
-
So in that quote, what they're saying is that you have to manually call those every time you make the changes? Why do the NSMutableArray methods not already publish those? – porglezomp Aug 01 '14 at 22:04
-
KVO was added to the language well after the first `NSArray` class, and it's very much a core class (i.e., performance is very important), so it makes sense it wasn't added. I'd be surprised if there weren't an open source project out there which provides an observable array class similar to what I mentioned as the second option. – Andrew Miner Aug 01 '14 at 22:06
-
For my purposes, this is definitely overboard (I went with just writing a setter method that does the work, since I only need to change the array one way.) but this is a very helpful answer for the question I asked. – porglezomp Aug 01 '14 at 22:42