How to create a Managed Object in Core Data

- by

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];


If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.