This post is intended to be a very brief introduction to Core Data. It just touches the most important points when setting up a core data stack.
The schema for the database is defined in my-project.xcdatamodeld
. This is where you tell CoreData what entities to expect and what attributes and relationships go in each entity. The .h and .m files for the entities can be generated automatically from the schema using XCode (some details here). Just open .xcdatamodel
file, click on the entity, and go to File
->New
->File
. Select the Core Data\NSManagedObject subclass
, and click Next, and then click Create again on the following view.
Its better to not play with these because they will be overwritten whenever you make changes in the schema and re-generate the files. To add custom methods and properties to these entities, I usually prefer creating categories on the entity (MyEntity+Extensions.h,m
).
I use MagicalRecord to perform CoreData requests. We could do it using the native CoreData APIs, but MagicalRecord makes it a lot easier and intuitive. Fetching from the database is done with the MR_
methods on the entity. e.g. [MyEntity MR_findAll]
will return an array of all news items in the database. Filtering can be done with predicates (e.g. this fetches all news for the given date).