繁体   English   中英

如何在Swift中的Core Data中保存多个项目

[英]How to save multiple items in Core Data in 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对象之后,执行类似的gameResult

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

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

链接到在这里说明的苹果文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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