O'Reilly logo

iOS 7 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

18.3. Creating and Saving Data Using Core Data

Problem

You have already created a managed object, and you want to instantiate it and insert that instance into your app’s Core Data context.

Solution

Follow the instructions in Recipe 18.1 and Recipe 18.2. Now you can use the insertNewObjectForEntityForName:inManagedObjectContext: class method of NSEntityDescription to create a new object of a type specified by the first parameter of this method. Once the new entity (the managed object) is created, you can modify it by changing its properties. After you are done, save your managed object context using the save: instance method of the managed object context.

I’ll assume that you have created a universal application in Xcode with the name Creating and Saving Data Using Core Data; now, follow these steps to insert a new managed object into the context:

  1. Find the implementation file of your app delegate.

  2. Import the Person.h file into the app delegate’s implementation file:

Note

Person is the entity we created in Recipe 18.1.

#import "AppDelegate.h"
#import "Person.h"

@implementation AppDelegate

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

<# Rest of your app delegate code goes here #>
  1. In the application:didFinishLaunchingWithOptions: method of your shared application delegate, write this code:

- (BOOL)            application:(UIApplication *)application
  didFinishLaunchingWithOptions: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required