简体   繁体   中英

How to save multiple items in Core Data in Swift

I have the following function using Core Data to segue the results to the 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)
}

I am able to show the Score in ScoreTableViewController thru:

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
}

However, when I restart the app, the DATA IS NO LONGER THERE.

I have seen this code to save the “totalScore” data:

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

However, how do I SAVE ALL of the data that I need? (For instance: datePlayed, totalScore, totalAnswered, totalDuration, and gameStatus)

The easiest way is to do something like this after you have populated the gameResult object with everything you wanted to save.

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

You need to call save on the appropriate managedObjectContext in order for the object to be stored.

Link to the apple docs that explains it here

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