背景:
游戏,在游戏结束时用户检索分数。调用函数将分数保存到DB
逻辑:
问题
它不断保存数据库中的新条目,而不是更新第一个条目。我只希望用户拥有一个随着他们不断获得更高分数而得到更新的条目。
我可以在任何地方看到localDB看看发生了什么吗?
这看起来也很冗长,有更简单的方法吗?
代码
func saveName(score: Int, whereToStore: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Scores")
//2
let entity = NSEntityDescription.entityForName("Scores",
inManagedObjectContext:managedContext)
let yourScore = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
/*Fetch results */
do
{
let fetchedResult = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
if let results = fetchedResult
{
if results.count > 1{
//Do some update code here if existing record in DB
print("Code to update number one result")
//yourScore.setValue(score, forKey: whereToStore)
let updateScore = results[0].valueForKey(whereToStore) as! Int
let updateScoreObject = results[0]
print("Score got back is \(updateScore)")
if (score > updateScore){
print("time to update")
updateScoreObject.setValue(score, forKey: whereToStore)
do {
try updateScoreObject.managedObjectContext!.save()
print("updated \(updateScoreObject)")
} catch {
let saveError = error as NSError
print(saveError)
}
}
} else {
// Do the saving here if you are a new user
//3
yourScore.setValue(score, forKey: whereToStore)
print("DOES THIS CODE RUN")
print("your score is\(yourScore)")
//4
do {
try managedContext.save()
//5
print("worked, I saved")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
}
else
{
print("Could not fetch result")
}
}
catch
{
print("There is some error.")
}
}
更新
加
let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
print("\(documentsUrl)")
所以我可以找到本地SQLite并使用数据库查看器打开,正如预期的那样它不断保存新条目而不是更新第一个