Use Restkit solely for mapping.

Skip to first unread message

Claire Poza

Apr 21, 2016, 10:19:18 AM4/21/16
to RestKit
I need to get my JSON on my own (b/c of crappy authentication requirements that I, for the life of me can't make work with restkit.)

Therefore I have my JSON, is there anyway to implement the mapping and conversion to coreData with restkit, and not include the objectmanagers that consume rest services?

Colin Morelli

Apr 26, 2016, 10:09:54 AM4/26/16
to RestKit

I've had a similar need before. You can definitely do this. You can map manually with (the below code is swift but it should be pretty straight forward to translate to Objective-C):

// you'll only want one instance of a managed object cache
let cache
= RKInMemoryManagedObjectCache(managedObjectContext: rootContext)
let operation
= RKMapperOperation(representation: data, mappingsDictionary: [NSNull(): mapping])
.mappingOperationDataSource = RKManagedObjectMappingOperationDataSource(managedObjectContext: mappingContext, cache: cache)

Note that in the above code, "data" represents the JSON that you want to map. "mappingsDictionary" represents a dictionary of source key path to the mapping that should be used for that data. Most of the time you'll just have [NSNull(): RKManagedObjectMapping] here, but an example of when you may need something else is if you, for example, wrap your API's response in an envelope:

"success": true,
"data": {
"id": "123",
"key": "value"

In this case, your mappingsDictionary would be ["data": mappingInstanceYouWantToUse]

Note that RKMapperOperation will not automatically save the NSManagedObjectContext on completion. You'll need to save after the operation is complete (you can use RKMapperOperation's delegate to receive events about the progress.

Final note - best practices suggest you'll want to use a child NSManagedObjectContext for each mapping operation. This ensures that you can always recover back to a consistent state in the case of a mapping failure (simply discard the temporary context). Simply call [mappingContext save]; on the mapping context to push it up to its parent store, and periodically flush the parent store out to disk per usual core data semantics.

Hopefully this helps.

Reply all
Reply to author
0 new messages