RestKit - 使用本地JSON文件同步数据库

时间:2014-10-24 21:55:33

标签: ios json core-data synchronization restkit-0.20

我提供了一个示例JSON文件(出于测试目的,我没有尽早访问Web服务)。加载文件并转换为NSDictionary后如何使用该字典并同步我的数据库?我读过的所有教程和示例都使用了Web服务

我已经为所有对象创建了我的映射并应用了它们之间的关系。

一个例子:

+ (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 个答案:

答案 0 :(得分:0)

以下是我的表现和效果:

 // 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作业是将值从源对象映射到目标对象 现在使用tableDic值更新表属性。 (表格类似于NSManagedObject