此代码:
NSString* MIMEType = @"application/xml";
[RKMIMETypeSerialization registerClass:[RKXMLReaderSerialization class] forMIMEType:MIMEType];
NSError* error = nil;
NSString* XMLString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]pathForResource:myLocallyStoredFileName ofType:@"xml"]
encoding:NSUTF8StringEncoding
error:nil];
NSData* XMLData = [XMLString dataUsingEncoding:NSUTF8StringEncoding];
id parsedData = [RKMIMETypeSerialization objectFromData:XMLData MIMEType:MIMEType error:&error];
if (parsedData == nil && error) {
// Parser error...
}
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[myCoreDataObject class]];
[mapping addAttributeMappingsFromDictionary:@{
... my mappings ...
}];
NSDictionary *mappingsDictionary = @{ [NSNull null]: mapping };
RKMapperOperation *mapper = [[RKMapperOperation alloc] initWithRepresentation:parsedData mappingsDictionary:mappingsDictionary];
NSError *mappingError = nil;
NSPersistentStoreCoordinator *psc = ((MPTAppDelegate *)[UIApplication sharedApplication].delegate).persistentStoreCoordinator;
NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
[context setPersistentStoreCoordinator:psc];
RKFetchRequestManagedObjectCache *cache = [RKFetchRequestManagedObjectCache new];
RKManagedObjectMappingOperationDataSource *source =
[[RKManagedObjectMappingOperationDataSource alloc]
initWithManagedObjectContext:context
cache:cache];
mapper.mappingOperationDataSource = source;
BOOL isMapped = [mapper execute:&mappingError];
if (isMapped && !mappingError) {
NSLog(@"Error");
}
给我以下错误:
CoreData:错误:无法在NSManagedObject类'myCoreDataObject'上调用指定的初始值设定项
就好像映射操作不知道我正在使用Core Data。我该如何解决这个问题?
答案 0 :(得分:1)
这是因为您的映射是RKObjectMapping
的一个实例,它应该是RKEntityMapping
的实例,以便与Core Data正确集成。创建映射时,然后提供Core Data实体而不是代表Class。
此外,您应该让RestKit为您管理Core Data堆栈。为此,创建类似于:
的堆栈NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
RKManagedObjectStore *managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:model];
NSError *error;
NSString *storePath = [RKApplicationDataDirectory() stringByAppendingPathComponent:@"XXXX.sqlite"];
NSPersistentStore *persistentStore = [managedObjectStore addSQLitePersistentStoreAtPath:storePath fromSeedDatabaseAtPath:nil withConfiguration:nil options:nil error:&error];
[managedObjectStore createManagedObjectContexts];
然后您将使用完全配置的managedObjectStore
。
(目前您还没有managedObjectStore
,因此您在评论中的代码中只是传递nil
)。