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

时间:2016-02-17 04:35:42

标签: ios swift core-data

我有以下函数使用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)

1 个答案:

答案 0 :(得分:0)

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

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

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

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