I'm working on a game and have some problem to store the best score ever for it. I'm using CoreData now, but every time I run the game, the score will compare with Int(17) and display the higher one. For which, the number 17 might be the first score I got when I ran the game. i.e. the highest score won't be stored then.
The code looks like this. Thank you!
// Decide if the game ends
var actionArray: NSMutableArray = NSMutableArray()
actionArray.addObject(SKAction.runBlock({
var transition:SKTransition = SKTransition.flipHorizontalWithDuration(0.5)
//Use CoreData
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext
var request = NSFetchRequest(entityName:"Score")
request.returnsObjectsAsFaults=false
request.predicate = NSPredicate(format:"fetchScore = %@","fetchScore")
var results:NSArray = context.executeFetchRequest(request, error: nil)
if (results.count > 0) {
var compareBest:Int = 0
var res = results[0] as NSManagedObject
compareBest = res.valueForKey("bestScore") as Int
if compareBest < self.score {
var newBestScore = NSEntityDescription.insertNewObjectForEntityForName("Score", inManagedObjectContext: context) as NSManagedObject
newBestScore.setValue("fetchScore", forKey:"fetchScore")
newBestScore.setValue(Int(self.score), forKey: "bestScore")
context.save(nil)
self.bestScore = self.score
}else{
self.bestScore = compareBest
}
}else{
var newBestScore = NSEntityDescription.insertNewObjectForEntityForName("Score", inManagedObjectContext: context) as NSManagedObject
newBestScore.setValue(Int(self.score), forKey: "bestScore")
newBestScore.setValue("fetchScore", forKey:"fetchScore")
context.save(nil)
self.bestScore = self.score
}
var gameOverScene:SKScene = GameOverScene(size: self.size, won: false, scored: self.score, best: self.bestScore)
self.view.presentScene(gameOverScene,transition:transition)
}))