Documentation Archive

Developer

Core Data Programming Guide

On This Page

Creating and Saving Managed Objects

After you have defined your managed object model and initialized the Core Data stack within your application, you are ready to start creating objects for data storage.

Creating Managed Objects

An NSManagedObject instance implements the basic behavior required of a Core Data model object. The NSManagedObject instance requires two elements: an entity description (an NSEntityDescription instance) and a managed object context (an NSManagedObjectContext instance). The entity description includes the name of the entity that the object represents and its attributes and relationships. The managed object context represents a scratch pad where you create the managed objects. The context tracks changes to and relationships between objects.

As shown in this example, the NSEntityDescription class has a class method that accepts a string for the name of the entity and a reference to the NSManagedObjectContext that the NSManagedObject instance will be associated with. The example defines the returning object as an AAAEmployeeMO object.

Objective-C

  1. AAAEmployeeMO *employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:[self managedObjectContext];

Swift

  1. let employee = NSEntityDescription.insertNewObjectForEntityForName("Employee", inManagedObjectContext: managedObjectContext) as! EmployeeMO

Creating NSManagedObject Subclasses

By default, Core Data returns NSManagedObject instances to your application. However, it is useful to define subclasses of NSManagedObject for each of the entities in your model. Speciflcally, when you create subclasses of NSManagedObject, you can define the properties that the entity can use for code completion, and you can add convenience methods to those subclasses.

To create a subclass of NSManagedObject, in the Xcode Core Data model editor, select the entity, and in the Entity pane of the Data Model inspector, enter the name in the Class field. Then create the subclass in Xcode.

Objective-C

  1. #import <CoreData/CoreData.h>
  2. @interface AAAEmployeeMO : NSManagedObject
  3. @property (nonatomic, strong) NSString *name;
  4. @end
  5. @implementation AAAEmployeeMO
  6. @dynamic name;
  7. @end

Swift

  1. import UIKit
  2. import CoreData
  3. import Foundation
  4. class EmployeeMO: NSManagedObject {
  5. @NSManaged var name: String?
  6. }

The @dynamic tag informs the compiler that the variable will be resolved at runtime.

After the subclass has been defined in your data model and added to your project, you can reference it directly in your application and improve the readability of your application code.

Saving NSManagedObject Instances

The creation of NSManagedObject instances does not guarantee their persistence. After you create an NSManagedObject instance in your managed object context, explicitly save that context to persist those changes to your persistent store.

Objective-C

  1. NSError *error = nil;
  2. if ([[self managedObjectContext] save:&error] == NO) {
  3. NSAssert(NO, @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
  4. }

Swift

  1. do {
  2. try managedObjectContext.save()
  3. } catch {
  4. fatalError("Failure to save context: \(error)")
  5. }

The call to save on the NSManagedObjectContext accepts a reference to an NSError variable and always returns either a success or a fail. If the save fails, it is important to display the error condition so that it can be corrected. The display of that error condition can be as simple as outputting the error to the console or as complicated as offering the error message to the user. If the save method returns a success, the error variable does not need to be consulted.