views:

162

answers:

1

I've got an NSArrayController bound to a mutable array in my controller, which manages an array of my model objects. The array controller is bound to my UI. It works well.

Now I'm trying to manually observe when a value changes in my model in my controller class (basically I'm marking the changed model as "needsToSave" for later on, but there are a few other tasks I have when it changes).

I've read up on KVO but I'm not entirely sure what I need to be observing... The NSArrayController? The array of objects? each model object itself? Confusion.

Any pointers would be very helpful. Thanks in advance!

+1  A: 

In your model item add and remove methods you should start and stop observing of each item in order to know about everything that happens. This will also help you implement undo. If you need sample code I know the Hillegass book covers it (at least 2nd edition did, have checked 3rd edition yet). You could also look for sample code for implementing undo for help.

theMikeSwan
So in my controller I'd have something like: `-addNewObject { MyObj *obj = ...; [obj addObsever:self ...]; [myArrayController addObject:obj];` Like that?
jbrennan
That is essentially correct, you do need to start observing for each key path you want to use `addObserver:self forKeyPath:aKeyPath options:NSKeyValueObservingOptionOld context:NULL`. Since you may need to observe multiple key paths you may want to make start and stop observing methods. Don't forget if you have (and you should) a setArray: method to enumerate through all items individually to stop observing the old array items and start on the new ones. BTW, if you are document based you can check to see if the doc is dirty to save on the 'needsToSave' part.
theMikeSwan