如何将多个条目保存到一个nsmangedObject

时间:2019-02-27 01:09:46

标签: ios swift core-data nsmanagedobject nsmanagedobjectcontext

我正在尝试将2个不同的字符串实体保存到核心数据中。然后在下面的表中显示我的函数,以保存数据。现在,该代码正在不同的表视图单元格上显示。意味着实体a正在显示在单元格1上,而实体b正在显示在单元格2上。它们没有被打印到同一单元格中。

var itemName2 : [NSManagedObject] = []
var itemName : [NSManagedObject] = []
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return itemName.count
}

func enterData() {
    let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
    let context = appDeldeaget.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Data", in: context)

    let theTitle = NSManagedObject(entity: entity!, insertInto: context)
    theTitle.setValue(hits.text, forKey: "hits")

    let theTitle2 = NSManagedObject(entity: entity!, insertInto: context)
    theTitle2.setValue(atBats.text, forKey: "atBATS")

    do {
        try context.save()
        itemName.append(theTitle)
        itemName.append(theTitle2)
    } catch {
        print("d")
    }
    self.theScores.reloadData()

    hits.text = ""
    hits.resignFirstResponder()
}

1 个答案:

答案 0 :(得分:0)

尝试一下

func enterData() {
    let appDeldeaget = UIApplication.shared.delegate as! AppDelegate
    let context = appDeldeaget.persistentContainer.viewContext
    let entity = NSEntityDescription.entity(forEntityName: "Data", in: context)

    let theTitle = NSManagedObject(entity: entity!, insertInto: context)
    theTitle.setValue(hits.text, forKey: "hits")

    //removed theTitle2 and set the second value in theTitle itself
    theTitle.setValue(atBats.text, forKey: "atBATS")

    do {
        try context.save()
        itemName.append(theTitle)
        //add theTitle only
    } catch {
        print("d")
    }
    self.theScores.reloadData()
    hits.text = ""
    hits.resignFirstResponder()
}