CoreData - 如何在swift中使用现有对象创建重复对象

时间:2017-06-18 06:49:52

标签: ios swift core-data magicalrecord

这是用于克隆现有对象的代码,但它在sourceSet.enumerated()

中的(_,relatedObject)行崩溃了
func clone(source:NSManagedObject,context:NSManagedObjectContext) -> NSManagedObject{
        let entityName = source.entity.name
        let cloned = NSEntityDescription.insertNewObject(forEntityName: entityName!, into: context) as! IZExperiment
        //loop through all attributes and assign then to the clone
    let attributes = NSEntityDescription.entity(forEntityName: entityName!, in: context)?.attributesByName
    for (attrKey, _) in attributes! {
        cloned.setValue(source.value(forKey: attrKey), forKey: attrKey)
    }


    //Loop through all relationships, and clone them.
    let relationships = NSEntityDescription.entity(forEntityName: entityName!, in: context)?.relationshipsByName
    for (relKey, relValue) in relationships! {
        if relValue.isToMany {
            let sourceSet = mutableOrderedSetValue(forKey: relKey)
            let clonedSet = (copy() as AnyObject).mutableOrderedSetValue(forKey: relKey)
//                let enumerator = sourceSet.enumerated()


            for (_,relatedObject) in sourceSet.enumerated()
            {
                let clonedRelatedObject = (relatedObject as! NSManagedObject).shallowCopy()
                clonedSet.add(clonedRelatedObject!)

            }

        } else {
            cloned.setValue(value(forKey: relKey), forKey: relKey)
        }
    }
    return cloned
}



extension NSManagedObject {
    func shallowCopy() -> NSManagedObject? {
        guard let context = managedObjectContext, let entityName = entity.name else { return nil }
        let copy = NSEntityDescription.insertNewObject(forEntityName: entityName, into: context)
        let attributes = entity.attributesByName
        for (attrKey, _) in attributes {
            copy.setValue(value(forKey: attrKey), forKey: attrKey)
        }
        return copy
    }
}

1 个答案:

答案 0 :(得分:0)

除了一些小错误之外,你有一个很大的错误:你忘了将克隆对象的多个关系设置为新创建的clonedSet。 另外,我建议使用更清晰的解决方案来创建clonedSet:

let clonedSet = Set(sourceSet.map {($0 as! NSManagedObject).shallowCopy()!}) 
cloned.setValue(clonedSet, forKey: relKey)

小错误: 您正在呼吁mutableOrderedSetValue(forKey:)value(forKey:)。在相应的对象上调用它们。

例如,source.mutableOrderedSetValue(forKey: relKey)代替mutableOrderedSetValue(forKey: relKey)

或者,在shallowCopy函数内,self.value(forKey: attrKey)而不是value(forKey: attrKey)

相关问题