【问题标题】:Trouble with fetching from core data and putting in array从核心数据中获取并放入数组的问题
【发布时间】: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


    【解决方案1】:

    for 循环中的范围是0...0 尝试0..&lt;list.count

    【讨论】:

    • 在故障排除之前我有过这样的循环。在帖子上改回来了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多