CoreData - 复制现有对象 [英] CoreData - Duplicate existing object
问题描述
您好,希望从我的核心数据db复制对象。现在我正在使用
Hi would like to duplicate an object from my core data db. Right now I'm using
movement2 = [NSEntityDescription
insertNewObjectForEntityForName:@"Movement"
inManagedObjectContext:self.managedObjectContext];
movement2.name = movement.name;
movement2.value = movement.value;
movement2.date = movement.date;
...
但是...
有没有办法将 move
的所有值复制到 NSManagedObject与NSObject不同,它提供了一个API来迭代它的一个代码?
Is there any way to copy all the values of movement
to movement2
, in one line of code?
推荐答案
其属性和关系。或者,而是实体描述。
NSManagedObject, unlike NSObject, provides an API to iterate over its attributes and relationships. Or, rather, it's entity description does. It isn't a one-liner, though.
movement2 = [NSEntityDescription insertNewObjectForEntityForName:@"Movement"
inManagedObjectContext:self.managedObjectContext];
NSEntityDescription *entity = [movement entity];
for (NSString *propertyName in [entity propertiesByName]) {
[movement2 setValue:[movement valueForKey:propertyName] forKey:propertyName];
}
查看文档。
这将足以克隆大多数对象。如果数据库结构正确,那么以这种方式复制关系,它们的反向关系也将被更新。所以,如果你的运动与MovementDirection有一个关系,而MovementDirection有一个反向的一对多关系 parentMovements
,这个 parentMovements
set将在调用上述代码后同时具有
运动
和 movement2
。
This will be enough to clone most of the objects. If database structure is correct, then copying relationships this way, their inverse ones will be updated as well. So, if your Movement had a relationship with, say, MovementDirection, and MovementDirection has an inverse 1-to-many relation parentMovements
, this parentMovements
set will have both movement
and movement2
inside after you call the code above.
这篇关于CoreData - 复制现有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!