In previous articles, you learned how to get started with Core Data, how to create a data model, and how to select and use data. However, you might ask, how do you create data using your data model in the first place? That's what this article answers.
Inserting New Data
Adding new data to your persistent store is a three-step process: create your new object; set the properties of your object; and save your object. Here's an example:
// Step 1: Create Object
CardStack * newStack = (CardStack *)[NSEntityDescription
insertNewObjectForEntityForName:@"CardStack"
inManagedObjectContext:managedObjectContext];// Step 2: Set Properties
[newStack setName:thisName];
[newStack setType:type];
[newStack setOrdering:[NSNumber numberWithInt:i]];// Step 3: Save Object
[self saveAction];
The most complex method call is insertNewObjectForEntityForName:inManagedObjectContext:, but as you can see you just pass it your class name and your context, and you'll get back a brand-new, empty copy of the class.
As you'll recall from the last article, every attribute and relationship is set as a property (and synthesized). Thus, all you need to do to define your new object is to set those properties, using dot syntax or the set: method calls, as you prefer.
Last, you must save your object. This is a requirement whenever you create or modify an object because by default your changes just occur in the managed object context, which you may recall from the first article in this series is a "whiteboard"; what you write there doesn't get saved to your persistent storage until you tell it to.
The saveAction method call is written into your appDelegate file by default when you create a Core Data project (as described in part one of this series). It's just a convenience function which activates the managedObjectContext's save: method and then reports any errors. Here's how it's currently defined in my projects:
- (void)saveAction {
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Unresolved Core Data Save error %@, %@", error, [error userInfo]);
exit(-1);
}
}
Clearly, the save: is what's really important.
Updating Information
You may not realize it, but you already have everything you need to update your data. In order to do so, you select data from your persistent storage (using the methodology discussed in the last article), make your changes, then save the results. Here's a simple example which selects every card and unorders them all:
-(void)unorderCards {
// Step 1: Select Data
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];NSEntityDescription *entity = [NSEntityDescription entityForName:@"Card"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];NSError *error;
NSArray *items = [self.managedObjectContext
executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];// Step 2: Update Object
for (Card *thisCard in items) {
[thisCard setDeckOrdering:[NSNumber numberWithInt:0]];
}// Step 3: Save Updates
[self saveAction];
}
In this example, I could have chosen either to save after every change to an object or to save only when I was done with all them. I decided I didn't ever want to have a partially unordered deck (if something interrupted the process), so I only saved when I was all the way done.
Deleting An Object
I suppose an article about using your Core Data dynamically wouldn't be complete without an explanation of how to delete things. It's very simple: you just send your managed object context a deleteObject: message:
[self.managedObjectContext deleteObject:managedObject];
You'll probably have retrieved this object with a fetchRequest, exactly as described in last article when talking about selection and in this article when talking about updating.
Next Up: Prefilling your data.

I just want to say I've read through all your Core Data postings and they've been EXTREMELY helpful. Especially coming from a SQL background. Thanks so much! :)
Posted by: Dave Gallagher | September 11, 2009 at 07:48 PM
thanks alot..... wonderful tutorials
Posted by: Arpit | September 12, 2009 at 06:25 AM
excuse me for being dense (maybe I should join Densa), but in your first line of code:
CardStack * newStack = (CardStack *)[NSEntityDescription
insertNewObjectForEntityForName:@"CardStack"
inManagedObjectContext:managedObjectContext];
Where does 'CardStack' come from? Is it automatically derived from the model? Or has an object been written which mirrors the structure of the model?
Posted by: jj | September 22, 2009 at 05:47 PM
I created an entity class, which is explained under a major head in Part 2. Otherwise, I just would have referenced a standard managed object class object.
Posted by: Shannon Appelcline | September 23, 2009 at 03:22 PM
Amazing tutorials set. Thank you so much..
greetings from Egypt
Posted by: Adham El-Shahabi | November 13, 2009 at 07:12 AM
OK, another member of Densa here. I've read this series a couple of times and seem to have missed something. In the model for my application, I have a class defined that has attributes and methods for doing certain operations. I want to use Core Data to store the instances of that class. So, I use the method you describe to create a managed object class. I see how I can instantiate the managed object class, but how do I get the data into my domain object? For example:
MyObject : NSObject // Domain class
int id;
NSString *text;
+(VOID) print (
printf(....);
}
MyDataObject // Core Data class
Attributes:
id int64
text String
Do I really have to instantiate both and manually copy the data from one place to the other? I'm hoping there's a simple way to associate these classes and that Core Data keeps up with the changes.
Posted by: Gerald Meazell | January 23, 2010 at 09:21 AM
Nevermind. It was covered in Part 2: Creating Entity Classes.
However, this has raised another question. Let's say I'm developing along, and I've generated my classes and have begun building my methods when I discover an attribute I didn't know I needed. If I do the File->New method, it overwrites my files, thus destroying my work on the methods. Is there an elegant way to make changes and integrate them?
Posted by: Gerald Meazell | January 23, 2010 at 09:37 AM
Please permit the Densa member to suggest an improvement to your code. When I tried what you did, it complained it "could not locate an NSManagedObjectModel" by the name of 'XYZ' in the context.
I initially thought I had to specify the name elsewhere, then I had an epiphany. When I changed the code to look like this:
CardStack * newStack = (CardStack *)[NSEntityDescription
insertNewObjectForEntityForName:@"CardStack"
inManagedObjectContext:[self managedObjectContext]];
It worked like a charm. The problem is that managedObjectContext is a variable that does not get initialized until you call the getter method and therein lies my chief complaint with Objective C: when you @synthesize a variable, the getter and setter methods have the same name as the variable. So, like in the case above, you think you're calling the method, but in reality you're accessing the variable directly. Putting it in brackets and prepending self calls the getter method, the context is initialized, and all is well.
Posted by: Gerald Meazell | January 24, 2010 at 04:54 PM
hi this is great content for I-U-D operations .
Can you tell how we create triggers on sqlite DB with manageable object.
Posted by: abhishekparauha@gmail.com | February 01, 2010 at 02:58 AM