CoreData - Duplicate existing object

后端 未结 3 1599
执笔经年
执笔经年 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:31

    I've made a rudimentary duplicate extension for NSManagedObject (based on @coverback's answer). Use with care (though for me it works so far)

    Swift 4:

    enum CopyBehavior {
        case none, copy, deepcopy
    }
    
    extension NSManagedObject {
        func duplicate(only: [String]) -> NSManagedObject {
            return duplicate { only.contains($0) ? .copy : .none }
        }
    
        func duplicate(except: [String], deep: [String] = []) -> NSManagedObject {
            return duplicate { deep.contains($0) ? .deepcopy : except.contains($0) ? .none : .copy }
        }
    
        func duplicate(byProperties fun: (String) -> CopyBehavior) -> NSManagedObject {
            let duplicate = NSEntityDescription.insertNewObject(forEntityName: entity.name!, into: managedObjectContext!)
    
            for propertyName in entity.propertiesByName.keys {
                switch fun(propertyName) {
                case .copy:
                    let value = self.value(forKey: propertyName)
                    duplicate.setValue(value, forKey: propertyName)
                case .deepcopy:
                    let value = self.value(forKey: propertyName)
                    if let value = value as? NSSet {
                        let copy = value.map {
                            return ($0 as! NSManagedObject).duplicate(byProperties: fun)
                        }
                        duplicate.setValue(copy, forKey: propertyName)
                    }
                    else if let value = value as? NSOrderedSet {
                        let copy = value.map {
                            return ($0 as! NSManagedObject).duplicate(byProperties: fun)
                        }
                        duplicate.setValue(NSOrderedSet(array: copy), forKey: propertyName)
                    }
                    else if let value = value as? NSManagedObject {
                        let copy = value.duplicate(byProperties: fun)
                        duplicate.setValue(copy, forKey: propertyName)
                    }
                    else {
                        fatalError("Unrecognized deepcopy attribute!")
                    }
                case .none:
                    break
                }
            }
    
            return duplicate
        }
    }
    

提交回复
热议问题