简体   繁体   中英

How to save multiple entries to one nsmangedObject

I am trying to save 2 different string entities to core data. Then display with a tableview my function below saves the data. Right now the code is being displayed on different tableview cells. Meaning entity a is being displayed on cell 1 and entity b is being displayed on cell 2. They are not being printed into the same cell.

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()
}

try this,

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM