The main view of my NSPersistentDocument based application is a table view (bound to an NSArrayController) showing the list of records, below it there is an "add record" button. I want the button to cause the following (supposedly trivial) behavior.
- Create an new object
- Set some defaults to the new object (that are stored in the main document and not available globally)
- Add it to the table view.
Here are the things that I tried or dismissed:
- use the NSArrayController "add" action - problem: will not return the new object and implementation is deferred so it is impossible to modify the newly created object
- Override the init of the data class - will not work - I need to access data that is stored in the document class instance
- Subclass NSArrayController and override "newObject" - again - will not work because I need to access data that is stored in the document.
Following code "almost" worked:
- (IBAction)newRecord:(id)sender { MyDataClass *newRecord = [recordsArrayController newObject];
}newRecord.setting1=self.defaultSetting1; newRecord.setting2=self.defaultSetting2; // ... etc... [recordsArrayController addObject:newRecord]; [recordsTable scrollRowToVisible:[recordsTable selectedRow]]; [newRecord release];
This code actually works well, for unsaved documents. But if I save the document and re-open it then clicking on the add button results in the new record showing twice in the table. Obviously the "addObject" is redundant (although it works fine in unsaved documents) but without it the new object is not selected.