Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone RestKit how to load a local JSON file and map it to a core data entity?

I'm building a two way dropbox sync app. I load objects from core data, convert them to JSON and send them over to dropbox. However, when I do sync, I compare a set of local JSON files to the dropbox JSON files. If a conflict is detected, a sync logic is applied. As a result of the sync logic, a remote JSON file may be downloaded and will replace the local JSON file.

So I end up with a bunch of JSON files in a local documents directory.

How can I use RestKit to deserialize local JSON files back into objects using mappings that I have defined ? The RKTwitterCoreData creates a core data entity from a web-based JSON. I'm trying to do the same with a local JSON file.

There are a bunch of loadObjects methods, but all of them appear to work with web calls:

- (RKObjectLoader*)loadObjectsAtResourcePath:(NSString*)resourcePath delegate:(id<RKObjectLoaderDelegate>)delegate;

Thank you !

like image 757
Alex Stone Avatar asked Apr 24 '12 20:04

Alex Stone


1 Answers

This is from Rest-Kit docs, Haven't tried it yet but it looks like the start as they use a JSON string.

You can find it here: look at the bottom of the page

NSString* JSONString = @"{ \"name\": \"The name\", \"number\": 12345}";
NSString* MIMEType = @"application/json";
NSError* error = nil;
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:MIMEType];
id parsedData = [parser objectFromString:JSONString error:&error];
if (parsedData == nil && error) {
    // Parser error...
}


RKObjectMappingProvider* mappingProvider = [RKObjectManager sharedManager].mappingProvider;
RKObjectMapper* mapper = [RKObjectMapper mapperWithObject:parsedData mappingProvider:mappingProvider];
RKObjectMappingResult* result = [mapper performMapping];
if (result) {
    // Yay! Mapping finished successfully
}

EDIT see rob5408 note about saving the context:

 [[RKObjectManager sharedManager].objectStore.managedObjectContext save:&error];
like image 155
shannoga Avatar answered Oct 19 '22 02:10

shannoga