Creating and Deleting Managed Objects

This article contains snippets you use when creating or deleting a managed object.

Creating a Managed Object

When you create a new managed object, you need to specify its entity. Typically, however, you don’t actually need access to the model directly. Instead, you can NSEntityDescription’s class method insertNewObjectForEntityForName:inManagedObjectContext: and pass the managed object context in which you want to create the new managed object. The method returns an instance of whatever class is defined in the managed object model to represent the entity, initialized with the default values given for its entity in the model.

To learn how to retrieve the managed object context, read “Getting a Managed Object Context.”

NSManagedObjectContext *context = <#Get the context#>;
<#Managed Object Class#> *newObject = [NSEntityDescription
    insertNewObjectForEntityForName:@"<#Entity name#>"
    inManagedObjectContext:context];

It is typically important to cast the new instance to the managed object class so that you can use the appropriate accessor methods without the compiler generating a warning (or, if you’re using dot syntax, an error).

Saving a Managed Object

Simply creating a managed object does not cause it to be saved to a persistent store. It is simply associated with the managed object context. To commit changes to the store, you send the context a save: message.

To learn how to retrieve the managed object context, read “Getting a Managed Object Context.”

NSManagedObjectContext *context = <#Get the context#>;
NSError *error;
if (![context save:&error]) {
    // Handle the error.
}

Deleting a Managed Object

Simply being deallocated does not cause a managed object to be deleted from the persistent store. To delete a managed object you have to delete it from the context then save the context.

To learn how to retrieve the managed object context, read “Getting a Managed Object Context”—or you can simply ask the object itself what context it belongs to.

NSManagedObject *aManagedObject = <#Get the managed object#>;
NSManagedObjectContext *context = [aManagedObject managedObjectContext];
[context deleteObject:aManagedObject];
NSError *error;
if (![context save:&error]) {
    // Handle the error.
}