[英]How to save one record for multiple department using core data in swift 3
[英]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.