我有一个托管对象(“A”),其中包含各种属性和关系类型,并且它的关系也有自己的属性和关系。我想做的是“复制”或“复制”以对象“A”为根的整个对象图,从而创建一个与“A”非常相似的新对象“B”。
更具体地说,“B”(或其子级)包含的任何关系都不应指向与“A”相关的对象。应该有一个全新的对象图,具有完整的相似关系,并且所有对象都具有相同的属性,但当然具有不同的 id。
有明显的手动方法可以做到这一点,但我希望了解一种更简单的方法,这在核心数据文档中并不完全明显。
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
关于cocoa - 如何复制 Core Data 托管对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2730832/