【发布时间】:2018-11-04 08:35:49
【问题描述】:
CoreData 结构: Entity: ZooAnimals, Attributes: animal (String type) and count (Integer 16 type)
我想保存一些动物名称和每只动物的数量(计数)。我可以通过对执行此操作所需的多个对象进行硬编码来做到这一点——参见下面的代码——但是我怎样才能更灵活地做到这一点,以便我可以只给它几个任意长度的数组并将它们保存到 CoreData 中(例如 @ 987654323@)
import UIKit
import CoreData
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
let managedContext = appDelegate.persistentContainer.viewContext
let animal1 = NSEntityDescription.insertNewObject(forEntityName: "ZooAnimals", into: managedContext)
let animal2 = NSEntityDescription.insertNewObject(forEntityName: "ZooAnimals", into: managedContext)
let animal3 = NSEntityDescription.insertNewObject(forEntityName: "ZooAnimals", into: managedContext)
let animal4 = NSEntityDescription.insertNewObject(forEntityName: "ZooAnimals", into: managedContext)
animal1.setValue("Donkey", forKey: "animal")
animal1.setValue(7, forKey: "count")
animal2.setValue("Horse", forKey: "animal")
animal2.setValue(3, forKey: "count")
animal3.setValue("Zebra", forKey: "animal")
animal3.setValue(9, forKey: "count")
animal4.setValue("Okapi", forKey: "animal")
animal4.setValue(2, forKey: "count")
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
}
【问题讨论】:
-
我尝试修改此答案,但无法正常工作。 stackoverflow.com/a/36194727/9684364