Core Data part 3 – Add Data

DEMO PROJECT

Given that,

1) You have your Data Stack set up
2) You have a model set up, and generated your model object which derives from NSManagedObject. Make sure your properties are @dynamic so that it uses the superclass’s synthesis (via NSManagedObject).

Remember, if you do not use @dynamic, and instead use @synthesize, it means you will be writing the getter/setter method yourself and if you do not write it correctly, the data you save using Core Data will not be there when you restart the app.

for xCode 7 and after, category file is generated

If you are using xCode 7 or after, a category file is generated along with the entity file like so:

  • Person+CoreDataProperties.h
  • Person+CoreDataProperties.m
  • Person.h
  • Person.m

The reason for this is because whenever new entity files are generated by doing:

  • click on .xcdatamodeld file
  • then Editor >> Create NSManagedObject subclass

you won’t have your Entity files overwritten. All your properties and methods will still be there. Instead, xCode will over-ride the Category file(s) instead.

Hence put all your code in Person, and leave the Category file alone.

Implementing the Entity files

Person.h

Person.m

Adding data

In your CoreDataStack.h, we’ll make 2 methods.

  1. create a new person
  2. display on all the people who’s in the database into our console.

Here are the few important issues when Adding a Person using core data:

1) use insertNewObjectForEntityForName method for Core Data to return you a managed object so you can initialize it with data.

2) Make sure you save context on it.

Here are the few important issues when fetching using core data:
executeFetchRequest gets what we need according to a request. It returns an array and you can iterative through it and display it.

ViewController button and responder

In your UIViewController, add a button and a responder method for both Adding a Person and Logging all the people to the console

Now let’s add a display button. Give it a responder method name displayAll.

Implement the button responders:

Now, go ahead and run the project using xcode. Press the Add Person button to add Person objects into the database, and see the results through your console.

Then press the display button to show all the Person objects that’s been saved into the database. Restart the app using your xcode project, press the display button again, and look at the log console to see the objects you’ve saved from before.