這個現有的對象重複的對象是克隆現有對象的代碼,但它在行sourceSet.enumerated()
CoreData - 如何創建具有迅速
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
}
}
到底是什麼錯誤?你能複製並粘貼在控制檯上打印的內容嗎? –