从核心数据中获取并放入数组时出现问题

时间:2017-03-20 05:39:05

标签: arrays swift xcode core-data

我正在尝试在核心数据中创建一个列表,该列表可以向实体添加“Person”两个属性:age(Int16)和name(string)。据我所知,我相信它是存储新对象,因为添加了新对象,但我不认为我的数组正确地获取它们。有人可以帮我弄清楚我哪里出错了。

    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")

    }
}

2 个答案:

答案 0 :(得分:0)

for循环中的范围为0...0 try 0..<list.count

答案 1 :(得分:0)

Person(context:context)在功能上与NSEntityDescription.insertNewObject (forEntityName: "Person",into: context) as NSManagedObject相同,因此您将对象插入核心数据两次。