For some conceptual reading, you may want to read documentation about Efficiently Importing Data, especially "Find-or-create". See a previous similar question.
Getting JSON and saving it as Core Data locally is highly reasonable. How I do it is in two stages:
- convert JSON to native Cocoa data types (NSDictionary and NSArray)
- convert NS* into Core Data object
Two good frameworks for converting between JSON and NS* are json-framework and TouchJSON. The below example is based on json-framework.
Let's say you get an array of some objects from JSON. You'd then do:
NSArray *objects = [jsonStringYouGotFromServer JSONValue];
for (NSDictionary *_object in objects) {
CDObjectType *cdObject = [self cdObjectFromDictionary:_object];
// cdObject is now a full-featured Core Data object
}
the cdObjectFromDictionary might be something like this:
- (CDObjectType *) cdObjectFromDictionary:(NSDictionary *)dict {
CDObjectType *object = [NSEntityDescription
insertNewObjectForEntityForName:@"Object"
inManagedObjectContext:moc];
NSDictionary *attributes = [[NSEntityDescription
entityForName:@"Object"
inManagedObjectContext:moc] attributesByName];
for (NSString *attr in attributes) {
[object setValue:[dict valueForKey:attr] forKey:attr];
}
return object;
}
The above assumes that the attribute names in your JSON and Core Data model are the same and that the data types match (i.e JSON numbers are Core Data NSNumbers etc). The above code works nicely even if the model changes.
The above code does not consider how to test if the object already exists locally, but you can imagine how to add that. You must have an object ID of some form in your model, and you can see if the object exists locally before adding it, or whether existing object needs to be updated.