【发布时间】:2017-08-11 07:30:50
【问题描述】:
我正在尝试在核心数据中创建一个列表,该列表可以向实体“Person”添加两个属性:年龄(Int16)和名称(字符串)。据我所知,我相信它会在添加新对象时存储新对象,但我认为我的数组没有正确获取它们。有人可以帮我弄清楚我哪里出错了。
var list = [Person(context:context)]
@IBAction func saveButton(_ sender: Any)
{
list.append(Person(context:context))
list[list.count-1].age = Int16(ageTF.text!)!
list[list.count-1].name = nameTF.text
let newList = NSEntityDescription.insertNewObject (forEntityName: "Person",into: context) as NSManagedObject
newList.setValue(list[list.count-1].name, forKey: "name")
newList.setValue(list[list.count-1].age, forKey: "age")
appDelegate.saveContext()
}
@IBAction func printList(_ sender: Any)
{
for index in 0...list.count-1
{
print("Name of person # \(index) = \(list[index].name!)")
print("Age of person # \(index) = \(list[index].age)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
do {
let results = try context.fetch(fetchRequest)
let listItems = results as! [NSManagedObject]
print(listItems)
}
catch {
print("Error")
}
}
【问题讨论】:
标签: arrays swift xcode core-data