我有一个托管对象(“A”),其中包含各种属性和关系类型,并且它的关系也具有自己的属性和关系。我想做的是“复制”或“复制”植根于对象“A”的整个对象图,从而创建一个非常类似于“A”的新对象“B”。
更具体地说,“B”(或其子代)包含的任何关系都不应指向与“A”有关的对象。应该有一个全新的对象图,它具有完整的相似关系,并且所有对象都具有相同的属性,但是ID却不同。
有一种明显的手动方法可以执行此操作,但是我希望了解一种更简单的方法,这在Core Data文档中并不完全清楚。
TIA!
最佳答案
这是我创建的用于执行托管对象的“深层复制”的类:属性和关系。请注意,这不会检查对象图中的循环。 (感谢Jaanus的出发点...)
@interface ManagedObjectCloner : NSObject {
}
+(NSManagedObject *)clone:(NSManagedObject *)source inContext:(NSManagedObjectContext *)context;
@end
@implementation ManagedObjectCloner
+(NSManagedObject *) clone:(NSManagedObject *)source inContext:(NSManagedObjectContext *)context{
NSString *entityName = [[source entity] name];
//create new object in data store
NSManagedObject *cloned = [NSEntityDescription
insertNewObjectForEntityForName:entityName
inManagedObjectContext:context];
//loop through all attributes and assign then to the clone
NSDictionary *attributes = [[NSEntityDescription
entityForName:entityName
inManagedObjectContext:context] attributesByName];
for (NSString *attr in attributes) {
[cloned setValue:[source valueForKey:attr] forKey:attr];
}
//Loop through all relationships, and clone them.
NSDictionary *relationships = [[NSEntityDescription
entityForName:entityName
inManagedObjectContext:context] relationshipsByName];
for (NSRelationshipDescription *rel in relationships){
NSString *keyName = [NSString stringWithFormat:@"%@",rel];
//get a set of all objects in the relationship
NSMutableSet *sourceSet = [source mutableSetValueForKey:keyName];
NSMutableSet *clonedSet = [cloned mutableSetValueForKey:keyName];
NSEnumerator *e = [sourceSet objectEnumerator];
NSManagedObject *relatedObject;
while ( relatedObject = [e nextObject]){
//Clone it, and add clone to set
NSManagedObject *clonedRelatedObject = [ManagedObjectCloner clone:relatedObject
inContext:context];
[clonedSet addObject:clonedRelatedObject];
}
}
return cloned;
}
@end