问题
I have provided with a sample JSON file (for testing purpose I haven't early access to the web service). after loading the file and converting to NSDictionary
how can I use that dictionary and sync my data base? all the tutorials and samples I've read use web service
I have created my mapping for all of the objects and applied their relationship.
an example:
+ (RKEntityMapping *) mapTableInManagedObjectStore:(RKManagedObjectStore *)managedObjectStore
{
RKEntityMapping *tableMapping = [RKEntityMapping mappingForEntityForName:@"Table" inManagedObjectStore:managedObjectStore];
tableMapping.identificationAttributes = @[@"tableID"];
[tableMapping addAttributeMappingsFromDictionary:@{
@"ID":@"tableID",
@"TableNumber":@"tableNumber",
@"NumberOfChairs":@"numberOfChairs"}];
return tableMapping;
}
回答1:
Here is how I did and works well:
// read file
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:contentPath encoding:NSUTF8StringEncoding error:NULL];
NSString* MIMEType = @"application/json";
NSError* parseError;
NSData *data = [myJSON dataUsingEncoding:NSUTF8StringEncoding];
id parsedData = [RKMIMETypeSerialization objectFromData:data MIMEType:MIMEType error:&parseError];
if (parsedData == nil && parseError) {
NSLog(@"Cannot parse data: %@", parseError);
}
//convert NSData to NSDictionary
NSError *errorJson=nil;
NSDictionary* responseDict = [NSJSONSerialization JSONObjectWithData:lookServerResponseData options:kNilOptions error:&errorJson];
NSDictionary *tableDic = responseDict;
//perform mapping
RKManagedObjectStore *managedObjectStore = [HAObjectManager sharedManager].managedObjectStore;
Table *table = [[Table findAll] firstObject];
RKManagedObjectMappingOperationDataSource *mappingDataSource = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:managedObjectStore.mainQueueManagedObjectContext cache:managedObjectStore.managedObjectCache];
RKMappingOperation *mappingOperation = [[RKMappingOperation alloc] initWithSourceObject:tableDic destinationObject:table mapping:[MappingProvider mapTablebjectStore:managedObjectStore]];
mappingOperation.dataSource = mappingDataSource;
NSError *error = nil;
[mappingOperation performMapping:&error];
RKMappingOperation job is to map values from source object to destination object.
now table attributes are updated with tableDic values. (table is kind of NSManagedObject
)
来源:https://stackoverflow.com/questions/26556883/restkit-sync-data-base-with-local-json-file