ios - 如何在 Swift 的核心数据中保存多个项目

标签 ios swift 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)

最佳答案

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

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

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

解释它的苹果文档链接 here

关于ios - 如何在 Swift 的核心数据中保存多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35448033/

相关文章:

ios - SCNPlane 上的 GADBannerView 可以吗?

swift - 如何在 swift 3 中设置默认样式

ios - 自定义 UITableView 标题部分

iphone - 在获取数组中选择单个字段以加载选择器

objective-c - 在不同的托管对象上下文中看不到 ios coredata 更新 - 上下文之间的数据不同

iphone - UILabel 中的行数

ios - 在 iOS SDK 中使用 BLE 从外部设备发送和接收数据

ios - onShouldStartLoadWithRequest 在 iOS React Native 中自动调用 WebView 中加载任何 url,如何控制它?

ios - 找不到谷歌地图

ios - NSPredicate 包含搜索包含数字和字母的字符串