我想将数组的元素保存到Core Data中,我尝试了许多不同的方法,但是没有一个方法没有保存所有元素但是从数组中保存了最后一个元素。我知道我在重写Core Data中的元素,但我没有添加新元素。我在下面写了一些我试过的方法。请以编程方式向我展示如何制作它?
let superArray = ["Steve", "Marina", "Tom", "Scarlett", "Michael", "David"]
@IBAction func saveData(sender: UIBarButtonItem) {
let personEntity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedObjectContext) as! NSManagedObject
var index = 0
while index < superArray.count {
personEntity.setValue(superArray[index], forKey: "namePerson")
managedObjectContext.save(nil)
index++
}
}
第二种方法。
let superArray = ["Steve", "John", "Tom", "Scarlett", "Michael", "David"]
@IBAction func saveData(sender: UIBarButtonItem) {
let personEntity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedObjectContext) as! NSManagedObject
var stringForSave: String!
for item in superArray {
stringForSave = item
// personEntity.setValue(item, forKey: "namePerson")
// managedObjectContext.save(nil)
}
personEntity.setValue(stringForSave, forKey: "namePerson")
managedObjectContext.save(nil)
}
第三种方法
var superArray = ["Steve", "John", "Tom", "Scarlett", "Michael", "David"]
@IBAction func saveData(sender: UIBarButtonItem) {
let personEntity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedObjectContext) as! NSManagedObject
for var index = 0; index < superArray.count; index++ {
var data = superArray[index]
personEntity.setValue(data, forKey: "namePerson")
managedObjectContext.save(nil)
}
}
答案 0 :(得分:1)
@IBAction func saveData(sender: UIBarButtonItem) {
for item in superArray {
let personEntity = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedObjectContext) as! Person
personEntity.namePerson = item
managedObjectContext.save(nil)
}
}