Enabling persistent object mapping is a relatively straight-forward process. It differs from transient object mapping in only a few ways:
- libRKCoreData.a must be linked into your target
- Apple’s CoreData.framework must be linked to your target
- A Data Model Resource must be added to your target and configured within Xcode
- The RestKit Core Data headers must be imported via #import <RestKit/CoreData/CoreData.h>
- An instance of RKManagedObjectStore must be configured and assigned to the object manager
- Persistent models inherit from RKManagedObject rather than RKObject
- Creates the object mapping targeting the Core Data entity with the specified name by RKManagedobjectMapping
- A Primary Key property must be defined by primaryKeyAttribute
Example for configuring the Core Data entities:
1. defining – product and product description
2. Configuring the Core Data object mapping.
The primaryKeyAttribute was defined the primary key for the table ‘MKG_PROD_DESC’.
The primaryKeyAttribute was defined the primary key for the table ‘MKG_PROD’. The hasOne relationship defined the relationship between product and product description.
Once these configuration changes have been completed, RestKit will load & map payloads into Core Data backed classes.
There are a couple of common gotchas and things to keep in mind when working with Core Data:
- You can utilize a mix of persistent and transient models within the application — even within the same JSON payload. RestKit will determine if the target object is backed by Core Data at runtime and will
return managed and unmanaged objects as appropriate. - RestKit expects that each instance of an object be uniquely identifiable via a single primary key that is present in the payload. This allows the mapper to differentiate between new, updated and removed objects.
- Apple recommends utilizing one managed object context instance per thread. When you retrieve a managed object context from RKManagedObjectStore, a new instance is created and stored onto thread local storage if the calling thread is not the main thread. You don’t need to worry about managing the life-cycle of the managed object contexts or merging changes — the object store observes these thread-local contexts and handles merging changes back into the main object context.
- RestKit assumes that you use an entity with the same name as your model class in the data model.
- There is not currently any framework level help for working with store migrations.