RestKit - Sync Data Base with local JSON file

有些话、适合烂在心里 提交于 2019-12-25 18:47:42

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!