【发布时间】:2016-01-18 22:34:06
【问题描述】:
我正在尝试使用 RestKit 将本地 XML 文件解析为 CoreData。我已经通过在线 REST 服务成功地做到了这一点,但是解析本地文件或仅仅解析 XML 似乎是完全不同的野兽。
首先我使用一个名为 CoreDataHandler 的类,它封装了所有默认的 CoreData 内容。所以它基本上就是 xcode 在 AppDelegate 中为您提供的,放入一个单独的类中。
到目前为止我做了什么:
CoreDataHandler* handler = [CoreDataHandler instance];
RKManagedObjectMappingOperationDataSource* dataSource = [[RKManagedObjectMappingOperationDataSource alloc] initWithManagedObjectContext:handler.managedObjectContext cache:sharedManager.managedObjectStore.managedObjectCache];
dataSource.operationQueue = [NSOperationQueue new];
NSString* filePath = [[NSBundle mainBundle] pathForResource:@"Seed_010000" ofType:@"xml"];
NSData *sourceObject = [NSData dataWithContentsOfFile:filePath];
RKObjectMapping* mapping = [self mapCourses];
RKMappingOperation* operation = [[RKMappingOperation alloc] initWithSourceObject:sourceObject destinationObject:nil mapping:mapping];
operation.dataSource = dataSource;
NSError* error = nil;
[operation performMapping:&error];
if( error == nil ) {
NSLog(@"%@", [operation mappingInfo]);
[handler saveContext];
} else {
NSLog(@"error: %@", error);
}
在此处创建映射:
+ (RKObjectMapping*) mapCourses {
RKEntityMapping *courseMapping = [RKEntityMapping mappingForClass:[Course class]];
[courseMapping addAttributeMappingsFromDictionary:@{ @"Name.text" : @"name" }];
RKEntityMapping* sectionMapping = [RKEntityMapping mappingForClass:[Section class]];
[sectionMapping addAttributeMappingsFromDictionary:@{ @"order" : @"order",
@"Icon.text" : @"icon",
@"Name.text" : @"name",
@"Description.text" : @"desc" }];
[courseMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"Sections" toKeyPath:@"sections" withMapping:sectionMapping]];
return courseMapping;
}
XML 文件如下所示:
<MyProject>
<Courses>
<Course>
<Name>Name of the Course</Name>
<Sections>
<Section order="0">
<Icon>ICON_00</Icon>
<Name>Name of the Section</Name>
<Description>Description of the Section</Description>
</Section>
</Sections>
</Course>
</Courses>
</MyProject>
我得到的错误是这样的:
2015-10-20 12:01:37.515 Training[16058:5400082] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSConcreteData 0x7fdf39f2b650> valueForUndefinedKey:]: this class is not key value coding-compliant for the key Sections.'
堆栈跟踪指向[操作 performMaping:&error];行。
我希望任何人都可以对此有所了解。
编辑:我改变了问题,因为第一个错误(关于错误的初始化程序是由于我自己的愚蠢。我使用 RKObjectMapping 而不是 RKEntityMapping,在使用 CoreData 时必须使用它。
【问题讨论】:
标签: ios objective-c xml core-data restkit