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:
Find the implementation file of your app delegate.
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"@implementationAppDelegate@synthesizemanagedObjectContext=_managedObjectContext;@synthesizemanagedObjectModel=_managedObjectModel;@synthesizepersistentStoreCoordinator=_persistentStoreCoordinator;<#Restofyourappdelegatecodegoeshere#>
In the
application:didFinishLaunchingWithOptions:method of your shared application delegate, write this code:
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access