2016-12-18 107 views
2

我想存儲一個有28個條目的數組到我的coreData。有沒有辦法做到這一點? 我用這段代碼試過了,但看起來這段代碼只是重寫了這個值。在CoreData中的Swift數組

let appDelegate = 
     UIApplication.shared.delegate as! AppDelegate 

    let managedContext = appDelegate.persistentContainer.viewContext 

    let entity = NSEntityDescription.entity(forEntityName: "PillTook", 
              in:managedContext) 

    let value = NSManagedObject(entity: entity!, 
           insertInto: managedContext) 

    for var index in 0...27 { 

     value.setValue(false, forKey: "took") 

     do { 
      try managedContext.save() 

      pillTook.append(value) 

     } catch let error as NSError { 
      print("Could not save \(error), \(error.userInfo)") 
     } 
    } 

回答

0

是的,你的代碼只創建一個NSManagedObject,並更新其took屬性for循環的價值。將let value = ...行移入for循環,爲每次迭代創建一個新的NSManagedObject。我還建議在for循環後只保存一次上下文,而不是在每次迭代中保存:

let appDelegate = UIApplication.shared.delegate as! AppDelegate 

let managedContext = appDelegate.persistentContainer.viewContext 

let entity = NSEntityDescription.entity(forEntityName: "PillTook", in:managedContext) 

for var index in 0...27 { 

    let value = NSManagedObject(entity: entity!, insertInto: managedContext) 
    value.setValue(false, forKey: "took") 
    pillTook.append(value) 
} 
do { 
    try managedContext.save() 
} catch let error as NSError { 
    print("Could not save \(error), \(error.userInfo)") 
} 
+1

非常感謝:) –