13.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 13.1 and Recipe 13.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:
Find the file named Creating_and_Saving_Data_Using_Core_DataAppDelegate.m.
Import the Person.h file into the app delegate’s implementation file:
Note
Person
is the entity we
created in Recipe 13.1.
#import "Creating_and_Saving_Data_Using_Core_DataAppDelegate.h" #import "Person.h" @implementation Creating_and_Saving_Data_Using_Core_DataAppDelegate @synthesize window = _window; @synthesize managedObjectContext = __managedObjectContext; @synthesize managedObjectModel = __managedObjectModel; @synthesize persistentStoreCoordinator = __persistentStoreCoordinator; ...
In the
application:didFinishLaunchingWithOptions:
method of your shared application delegate, ...
Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.