tags:

views:

87

answers:

1

I have a small core data app. I have a subclass of an NSObjectController acting as the binding between the view and the model and a NSTextField on the view for the user to type into.

When the window opens the text field is editable because I have the bindings set to my subclassed NSObjectController, controller key to "content" and the Model Key Path to an attribute of my Entity.

If I type in some text, save the file and reopen it the text in the NSTextField isn't there.

For testing, I have a button connected to the add: selector of the controller and when you press the button everything works fine - you can enter text into a NSTextField, you can save the document, you can open it again.

How do I prepare the object when the nib loads?

In my init method in my subclass of the NSObjectController I have:

[self setAutomaticallyPreparesContent:YES];

and then I have in MyDocument:windowControllerDidLoadNib (oc is the IBOutlet to the subclassed objectcontroller in IB):

[oc fetchWithRequest:nil merge:NO error:&error];

but it didn't work. I need to create the content so the user can get started typing.

Thanks

A: 

OK, here's my contribution. I'm happy to be able to answer something! I found this in the "NSPersistentDocument Core Data Tutorial" in the documentation.

Remember, my problem was when the document is created I want to create an NSManagedObject. That way the user doesn't have to hit the "add" button. I don't want the document to be dirty (until the user types something) and I don't want to replace the content if I'm opening a saved file. This needs to happen only when a new document is created.

NSDocument provides a method:

initWithType:error:

to accomplish this.

1) grab the managedObjectContext,

2) turn off undo for the moment. This prevents the doc from being dirty and preventing the user from undoing the creation and insertion of the Entity.

3) use insertNewObejctForEntityForName:inManagedObjectContext

4) install the changes

5) turn back on undo

Here's the code:

- (id)initWithType:(NSString *)typeName error:(NSError **)outError
{
    self = [super initWithType:typeName error:outError];
    if (self != nil) {
        NSManagedObjectContext *managedObjectContext = [self managedObjectContext];

        [[managedObjectContext undoManager] disableUndoRegistration];

        self.myManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"myEntityName" 
                                                      inManagedObjectContext:managedObjectContext];

        [managedObjectContext processPendingChanges];

        [[managedObjectContext undoManager] enableUndoRegistration];
        NSLog(@"initWithType");
    }
    return self;
}  
Mark