2017-06-18 73 views
0

這個現有的對象重複的對象是克隆現有對象的代碼,但它在行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 
    } 
} 
+1

到底是什麼錯誤?你能複製並粘貼在控制檯上打印的內容嗎? –

回答

0

其他墜毀的(_,則relatedObject),比一些小錯誤,你有一個很大的問題:你忘記將克隆對象的關係設置爲新創建的克隆集。 另外,我建議創建一個clonedSet清潔的解決方案:

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

的小錯誤: 您是在稀薄的空氣中調用mutableOrderedSetValue(forKey:)value(forKey:)。在適當的對象上調用它們。

例如,mutableOrderedSetValue(forKey: relKey)

source.mutableOrderedSetValue(forKey: relKey)代替或者,shallowCopy FUNC裏面的self.value(forKey: attrKey)代替value(forKey: attrKey)

+0

感謝SimSim我會盡力檢查 –