CoreData - Duplicate existing object

后端 未结 3 1646
执笔经年
执笔经年 2021-02-11 06:16

Hi would like to duplicate an object from my core data db. Right now I\'m using

        movement2 = [NSEntityDescription
                                     ins         


        
3条回答
  •  没有蜡笔的小新
    2021-02-11 06:43

    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];
    }
    

    See the documentation for more details.

    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.

提交回复
热议问题