Insert records with NSManagedObject and Xcode

 

Example code how to insert records / objects into a database with Xcode and the NSManagedObject.
Using:
Xcode 4.2.1
Mac OS X 10.7.2
Cocoa
 
First add a entity to your database for example Person, add to this entity the Attributes firstName and lastName of type string.
 
Create a NSManagedObjectContext.

NSManagedObjectContext *context = [self managedObjectContext];

 

Now create a NSManagedObject newPerson and set the insertNewObjectForEntityForName to Person.
Set inManagedObjectContext to context.

NSManagedObject *newPerson = [NSEntityDescription

                                       insertNewObjectForEntityForName:@"Person"

                                       inManagedObjectContext:context];             

 

 
Set the values of firstName and lastName for the object newPerson

 

[newPerson setValue:@"Mark" forKey:@"firstName"];

[newPerson setValue:@"Finder" forKey:@"lastName"];

 
Now save the NSManagedObject to the database.

NSError *error;

if (![context save:&error]) 

{

    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);

}