【问题标题】:How to save multiple items in Core Data in Swift如何在 Swift 中的 Core Data 中保存多个项目
【发布时间】:2025-12-04 08:25:01
【问题描述】:

我有以下函数使用 Core Data 将结果传递给 ScoreTableViewController:

func showScore(){

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let gameResult = NSEntityDescription.insertNewObjectForEntityForName("SaveGame", inManagedObjectContext: appDelegate.managedObjectContext) as! ScoreHistory

    gameResult.datePlayed = self.dateToday
    gameResult.totalScore = self.scorepassed
    gameResult.totalAnswered = self.numberofquestions
    gameResult.totalDuration = self.totalduration
    gameResult.gameStatus = self.gameStatus

    self.performSegueWithIdentifier("scoreListSegue", sender: self)
}

我可以通过以下方式在 ScoreTableViewController 中显示分数:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell

    if let game = fetchedResultsController!.objectAtIndexPath(indexPath) as? ScoreHistory {
        cell.textLabel?.text = "Date: \(game.datePlayed!) | Score: \(game.totalScore!)/\(game.totalAnswered!) | \(game.totalDuration!) | \(game.gameStatus!)"

    }
    return cell
}

但是,当我重新启动应用程序时,数据不再存在。

我看过这段代码来保存“totalScore”数据:

func saveScore(saveTotalScore: String){

    let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let entity = NSEntityDescription.entityForName("SaveGame", inManagedObjectContext: managedContext)
    let totalScore = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
    totalScore.setValue(saveTotalScore, forKey: "totalScore")

    do {
        try managedContext.save()
        scoreData.append(totalScore)
    }
    catch {
        print("error")
    }
}

但是,如何保存我需要的所有数据? (例如:datePlayed、totalScore、totalAnswered、totalDuration 和 gameStatus)

【问题讨论】:

    标签: ios swift core-data


    【解决方案1】:

    最简单的方法是在您将要保存的所有内容填充到 gameResult 对象之后执行类似的操作。

     do {
       try appDelegate.managedObjectContext.save()
     } catch {
        fatalError("Failure to save context: \(error)")
     }
    

    您需要在适当的 managedObjectContext 上调用 save 才能存储对象。

    链接到解释它的苹果文档here

    【讨论】:

      最近更新 更多