codeconverter
codeconverter

Reputation: 56

CoreData - How to create duplicate object with existing object in swift

This is the code for cloning the existing object but it crashed in line for (_,relatedObject) in sourceSet.enumerated()

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

Upvotes: 0

Views: 1358

Answers (1)

SimSim
SimSim

Reputation: 170

Other than a few minor bugs, you have a big one: you forgot to set the to many relationship(s) of the cloned object to the newly created clonedSet. Also, I suggest a cleaner solution for creating the clonedSet:

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

The minor bugs: You are calling mutableOrderedSetValue(forKey:) and value(forKey:) on thin air. Call them on the appropriate object.

For example, source.mutableOrderedSetValue(forKey: relKey) instead of mutableOrderedSetValue(forKey: relKey)

Or, inside the shallowCopy func, self.value(forKey: attrKey) instead of value(forKey: attrKey)

Upvotes: 1

Related Questions