【发布时间】:2014-03-10 20:23:19
【问题描述】:
在我的 iOS 应用程序中,我正在对实体进行重量级迁移,其中我将属性的类型从旧数据模型中的 Integer64 转换为新数据模型中的 String 类型。此属性的转换似乎工作正常。但是,我遇到的问题是同一个实体的另一个属性为空(它应该是),当这个属性被迁移到新模式中的同一个实体时,一个错误被标记:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "date"; desired type = NSDate; given type = NSNull; value = <null>.'
我不确定为什么要标记此错误,因为该属性在数据模型中被标记为可选。我想简单地将属性的 nil 值“按原样”迁移到新数据模型中的相同属性,而不进行任何更改或修改。
这是我正在使用的 NSEntityMigrationPolicy 子类的相关代码:
- (BOOL)createDestinationInstancesForSourceInstance:(NSManagedObject *)sInstance entityMapping:(NSEntityMapping *)mapping manager:(NSMigrationManager *)manager error:(NSError *__autoreleasing *)error {
NSManagedObject *newObject;
NSEntityDescription *sourceInstanceEntity = [sInstance entity];
//correct entity? just to be sure
if ([[sourceInstanceEntity name] isEqualToString:@"MyEntity"]) {
newObject = [NSEntityDescription insertNewObjectForEntityForName:@"MyEntity" inManagedObjectContext:[manager destinationContext]];
//obtain the attributes
NSDictionary *keyValDict = [sInstance committedValuesForKeys:nil];
NSArray *allKeys = [[[sInstance entity] attributesByName] allKeys];
//loop over the attributes
for (NSString *key in allKeys) {
//get key and value
id value = [keyValDict objectForKey:key];
if ([key isEqualToString:@"integerType"]) {
//here retrieve old value
NSNumber *oldValue = [keyValDict objectForKey:key];
//here do conversion as needed
NSString *stringType = [oldValue stringValue];
//then store new value
[newObject setValue:stringType forKey:key];
} else { //no need to modify the value, Copy it across -- this is where I believe the problem is
[newObject setValue:value forKey:key];
}
}
[manager associateSourceInstance:sInstance withDestinationInstance:newObject forEntityMapping:mapping];
}
return YES;
}
谁能看出我做错了什么?
【问题讨论】: