How to create a Managed Object in Core Data

Assuming you’re using an app template that includes Core Data, you will have access to the Managed Object Context. In the simplest form, and without custom Entity classes setup, you can use key/value coding to set your object’s properties. In fact, the Master/Detail template does this.

Here’s an example for an Entity named Event with two properties (myKey and anotherKey):

// create a managed object
NSManagedObject *myObject = [NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
    
// set its attributes
[myObject setValue:@"This is my value" forKey:@"myKey"];
[myObject setValue:@"My other value" forKey:@"anotherKey"];

If you have created custom NSManagedObject subclasses for your Entity then you can create an object like this:

// create a managed object from my custom class
Event *myObject = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:self.managedObjectContext];
    
// set my object's properties
myObject.myKey = @"This is my value";
myObject.anotherKey = @"My other value";

The KVC method will always work, regardless if you have custom classes or not. Custom Classes have the advantage that you can add custom behaviour (i.e. methods), and of course code completion in Xcode.

Note that these snippets will create an object, but your values are only stored once you save the Managed Object Context:

[self.managedObjectContext save:nil];




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.