从官网的文档我们知道,实例化NSManagedObject不能像一般的nsobject一样[[NSManagedObject alloc] init],这样运行时会出错,正确的方法是:
[NSEntityDescription insertNewObjectForEntityForName:entity inManagedObjectContext:[db managedObjectContext]] 或
[[NSManagedObject alloc] initWithEntity:entity inManagedObjectContext:[db managedObjectContext]]
返回的实例。
如果我们想把一个实列的值copy到另一个实例,如何做呢,我们可以根据属性,一个一个copy,但是代码不灵活,如果我们改了数据库字段,那么代码又要改,我发现了一个通用的代码。
- (NSManagedObject*)copyObject:(NSManagedObject*)object
toContext:(NSManagedObjectContext*)moc
parent:(NSString*)parentEntity;
{
NSString *entityName = [[object entity] name];
NSManagedObject *newObject = [NSEntityDescription
insertNewObjectForEntityForName:entityName
inManagedObjectContext:moc];
[[self lookup] setObject:newObject forKey:[object objectID]];
NSArray *attKeys = [[[object entity] attributesByName] allKeys];
NSDictionary *attributes = [object dictionaryWithValuesForKeys:attKeys];
[newObject setValuesForKeysWithDictionary:attributes];
id oldDestObject = nil;
id temp = nil;
NSDictionary *relationships = [[object entity] relationshipsByName];
for (NSString *key in [relationships allKeys]) {
NSRelationshipDescription *desc = [relationships valueForKey:key];
NSString *destEntityName = [[desc destinationEntity] name];
if ([destEntityName isEqualToString:parentEntity]) continue;
if ([desc isToMany]) {
NSMutableSet *newDestSet = [NSMutableSet set];
for (oldDestObject in [object valueForKey:key]) {
temp = [[self lookup] objectForKey:[oldDestObject objectID]];
if (!temp) {
temp = [self copyObject:oldDestObject
toContext:moc
parent:entityName];
}
[newDestSet addObject:temp];
}
[newObject setValue:newDestSet forKey:key];
} else {
oldDestObject = [object valueForKey:key];
if (!oldDestObject) continue;
temp = [[self lookup] objectForKey:[oldDestObject objectID]];
if (!temp && ![destEntityName isEqualToString:parentEntity]) {
temp = [self copyObject:oldDestObject
toContext:moc
parent:entityName];
}
[newObject setValue:temp forKey:key];
}
}
return newObject;
}
源码来自:
http://pastebin.com/efkji4sy