GangstaGraham
GangstaGraham

Reputation: 9355

Difficulty in creating Core Data managed objects

At the moment I can't see any AUser objects in my sqlite3 app database.

This is the code I have to create a user. Am I missing something? There are no warnings/errors with the code.

AUser *user = [NSEntityDescription insertNewObjectForEntityForName:@"AUser" inManagedObjectContext:_managedObjectContext];  // _managedObjectContext is declared elsewhere

user.name = username;  //username is some string declared elsewhere / name is an attribute of AUser

Upvotes: 1

Views: 95

Answers (3)

Lorenzo B
Lorenzo B

Reputation: 33428

You need to perform a save on the context.

NSError* error = nil;
if(![context save:&error]) {        
    // something went wrong
    NSLog(@"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
    abort();
}

When you perform a save, data in the context are saved to the persistent store coordinator (hence in your sql store).

P.S. Based on the discussion with @G. Shearer, in production if the context fails to save, you can handle the error gracefully. This means not using abort() call that causes the app to crash.

NSError* error = nil;
if(![context save:&error]) {        
    // save failed, perform an action like alerting the user, etc.
} else {
    // save success
}

Upvotes: 4

G. Shearer
G. Shearer

Reputation: 2185

you need to call

NSError *error = nil;
[_managedObjectContext save:&error];
if(error != nil) NSLog(@"core data error: %@",[[error userInfo] description]);

before the object will be persisted to the database

Upvotes: 1

melsam
melsam

Reputation: 4977

You need to call save after creating the object. Example:

NSError *error;
if ([user.managedObjectContext save:&error]) {
    //Success!
} else {
    //Failure. Check error.
}

Upvotes: 3

Related Questions