NSUserDefaults valueForKey error - swift

I am trying to save a highscore in a simple game. I am new to swift 2 and not sure what I am doing wrong. i am getting the error that "Value of type 'int' has no member for 'valueForKey'. Here is my code as of my last unsuccesful attempt.
var highScoreDefault = NSUserDefaults.standardUserDefaults()
if(highScoreDefault.valueForKey("highScore") != nil){
highScore = highScore.valueForKey("highScore") as NSInteger! //error here
}
newFunc
score += 1
if (score > highScore){
highScore = score
var highScoreDefault = NSUserDefaults.standardUserDefaults()
highScoreDefault.setValue(highScore, forKey: "highScore")
highScoreDefault.synchronize()
}
highscoreLbl.text = "\(highScore)"

You have to save it like :NSUserDefaults.standardUserDefaults().setInteger(highScore, forKey: "highScore")
and retrieve it like : var highScore: Int = NSUserDefaults.standardUserDefaults().integerForKey("highScore")

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(value, forKey: "highScore")
Apple recommends to only call synchronize() in special circumstances like when the app is about to exit.
The synchronize() method, which is automatically invoked at periodic
intervals, keeps the in-memory cache in sync with a user’s defaults
database.

Its very simple to set value in NSUserDefault
NSUserDefaults.standardUserDefaults().setInteger(yourScore, forKey: "highScore")
NSUserDefaults.standardUserDefaults().synchronize()

Try this one:
let highScoreDefault = NSUserDefaults.standardUserDefaults()
//Set
highScoreDefault.setInteger(yourInt, forKey: "intKey")
highScoreDefault. synchronize()
//Get
highScoreDefault.integerForKey("intKey")

Related

Thread 1: EXC_BAD_INSTRUCTION when encoding data in UserDefaults (Swift)

Hi, I am trying to save data in Userdefaults but whenever I run this page of the app I am getting Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOC) as shown in the image.
Prior to this, I was getting the same exact error on the line beneath the one that I am getting it on right now, but now it is coming on this current line as seen in the image. How can I fix this to save my data every time the app launches?
var highScore = 0
var bronzeStatus = 0
ViewDidLoad:
let defaults = UserDefaults.standard
highScore = defaults.value(forKey: "Add1High") as! NSInteger!
bronzeStatus = defaults.value(forKey: "bronzeMed") as! NSInteger!
Underneath:
if correctNumber > highScore {
highScore = correctNumber
let defaults = UserDefaults.standard
defaults.setValue(highScore, forKey: "Add1High")
defaults.synchronize()
}
if highScore >= 15 {
let defaults = UserDefaults.standard
let bronzeAlert = UIAlertController(title: "New Medal!", message: "You earned a bronze medal!", preferredStyle: UIAlertControllerStyle.alert)
bronzeAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(scoreAlert, animated: true, completion: nil)
bronzeStatus = 1
defaults.setValue(bronzeStatus, forKey: "bronzeMed")
defaults.synchronize()
}
Try using
highScore = defaults.integer(forKey: "Add1High")
it converts the returned value to an NSInteger. If the value is an NSNumber, the result of -integerValue will be returned. If the value is an NSString, it will be converted to NSInteger if possible. If the value is absent or can't be converted to an integer, 0 will be returned. So no need to convert on your part.
Also while setting use
defaults.set(highScore, forKey: "Add1High")
Swift 3.0 code
this code work parfect..
var highScore = 0
var bronzeStatus = 0
ViewDidLoad:
//set integer type data
UserDefaults.standard.set(20, forKey: "Add1High")
UserDefaults.standard.set(30, forKey: "bronzeMed")
//Get integer type data
let defaults = UserDefaults.standard
highScore = defaults.integer(forKey: "Add1High")
bronzeStatus = defaults.integer(forKey: "bronzeMed")
print("\(highScore)\(bronzeStatus)") //2030
use this to check your userdefaults value exits or not
let defaults = UserDefaults.standard
if defaults.value(forKey: "Add1High") != nil{
highScore = defaults.value(forKey: "Add1High") as! NSInteger!
}
if defaults.value(forKey: "bronzeStatus") != nil{
bronzeStatus = defaults.value(forKey: "bronzeStatus") as! NSInteger!
}
Because you have condition
if correctNumber > highScore{}
so this part may execute or maybe not ,so you have to check for that

Using UserDefaults to save a high score in swift

I"m trying to get a high score to save each time the player exits the app, but I'm struggling to get it to work and I'm confused as to where I'm making a mistake.
var gameSettings = Settings.sharedInstance
let HIGHSCORE = "HIGHSCORE"
if gameSettings.highScore < score{
gameSettings.highScore = score
UserDefaults.standard.set(gameSettings.highScore, forKey: HIGHSCORE)
}
if gameSettings.highScore >= score{
gameSettings.score = score
}
let gameOverHighScore = SKLabelNode()
gameOverHighScore.name = "gameOverHighScore"
gameOverHighScore.fontName = "Helvetica Neue UltraLight"
if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) {
gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M"
}
gameOverHighScore.fontColor = SKColor.white
gameOverHighScore.position = CGPoint(x: 0, y: -175)
gameOverHighScore.fontSize = 70
gameOverHighScore.zPosition = 52
addChild(gameOverHighScore)
In if let HIGHSCORE = UserDefaults.standard.value(forKey: HIGHSCORE) {
gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M"
}
you are try find value in UserDefaults not by key HIGHSCORE, but by new value HIGHSCORE of type ANY. If you want to fix it, you can do like this:
if let HIGHSCORE = UserDefaults.standard.value(forKey: self. self.HIGHSCORE) as! Int {
gameOverHighScore.text = "HIGHSCORE : \(HIGHSCORE)M" }
or you can unwrap value in new value with another name. And don't forget to cast value to appropriate type or use
UserDefaults.standard.integer(forKey: self.HIGHSCORE)
Here is a simple example on how to do it:
let firebaseId = user.uid // Variable we want to save
UserDefaults.standard.set(firebase, forKey: "firebase") // Saving the variable with key "firebase"
And now to retrieve:
if let firebaseId = UserDefaults.standard.string(forKey: "firebase") {
print("Firebase ID: \(firebase)")
}
On your code, you are retrieving to HIGHSCORE, and you should be retrieving to something like gameSettings.highScore (Based on what I can infer from your code)

Cannot get the dictionary from NSUserDefaults as saved format

I want to get a swift dictionary from NSUserDefaults as the format that I've saved before. I've saved the dictionary as [String:String] format, but while I'm getting the dictionary with dictionaryForKey(key) method I got [String:AnyObject]?. How can I convert [String:AnyObject]? to [String:String] or how can I get the dictionary in right format?
Saving to NSUserDefaults
var tasks: Dictionary<String,String> = [:]
let defaults = NSUserDefaults.standardUserDefaults()
let key = "key"
defaults.setObject(tasks, forKey: key)
defaults.synchronize()
Getting from NSUserDefaults
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingArray = defaults.dictionaryForKey(key)
If you've registered it with a default value so it never can be nil, just downcast it to the proper type
let defaults = NSUserDefaults.standardUserDefaults()
let key = "ananZaa"
let incomingDictionary = defaults.objectForKey(key) as! Dictionary<String,String>

NSUserDefaults for high score is not working on iOS 8 Simulator?

I've tried to synchronize the saved data but my game still does not store the highest score. I can't find whats wrong with the replacing of the highScore with score if it is higher. Sorry I'm a beginner who just started learning iOS programming.
init(size: CGSize, score: NSInteger) {
super.init(size: size)
self.backgroundColor = SKColor.whiteColor()
//To save highest score
var highscore = 0
let userDefaults = NSUserDefaults.standardUserDefaults()
if (score > highscore){
NSUserDefaults.standardUserDefaults().setObject(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as! Int
//To get the saved score
var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as! Int
Let's step through your code.
First, you overwrite whatever the high score was with 0:
//To save highest score
let highscore = 0
let userDefaults = NSUserDefaults.standardUserDefaults()
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
Then, you're checking if "highscore" is in the defaults:
if let highscore: AnyObject = userDefaults.valueForKey("highscore") {
A few notes:
This will always be true because you just set it
You should be using objectForKey(_:), not valueForKey(_:)
But really you should be using integerForKey(_:) not objectForKey(_:), since highscore is always an Int.
You can delete : AnyObject because objectForKey(_:) returns AnyObject?
Then, we go into the code:
NSUserDefaults.standardUserDefaults().setObject(score, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
You are now overwriting the 0 score you just added earlier with whatever score is.
Finally, your else block, which will never get called, sets highscore, even though you just did that before the if condition.
}
else {
NSUserDefaults.standardUserDefaults().setObject(highscore, forKey: "highscore")
NSUserDefaults.standardUserDefaults().synchronize()
}
It's not clear from your code what you want to do, but you did say this in your question:
I can't find whats wrong with the replacing of the highScore with score if it is higher.
Well, for one thing, you're never checking which one is higher.
I think you might be trying to do this:
let defaults = NSUserDefaults.standardUserDefaults()
let highscore = defaults.integerForKey("highscore")
if score > highscore {
defaults.setInteger(score, forKey: "highscore")
defaults.synchronize()
}

saving key and value pairs swift

I need a way to save key and value pairs in swift for my application. I am new to IOS programming, but I know Android and I am looking for something like shared preferences in android, but for swift. By "save," I mean that when the user quits out of the application, the key and value pairs are saved in the local data.
Swift 3.0
Saving Data:
let userDefaults = UserDefaults.standard
userDefaults.set(yourKey, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = UserDefaults.standard.object(forKey: "yourKey") as AnyObject? { }
What you are looking for is called "Userdefaults" - you can use them like this:
Saving Data:
let userDefaults = NSUserDefaults.standardUserDefaults()
userDefaults.setObject(variable, forKey: "yourKey")
userDefaults.synchronize()
Reading Data:
if let yourVariable: AnyObject = NSUserDefaults.standardUserDefaults().objectForKey("yourKey") {
....
Here you find more information:
https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/index.html
Working way for Swift 3+:
// Storing values
UserDefaults.standard.set(true, forKey: "KeyName") // Bool
UserDefaults.standard.set(1, forKey: "KeyName") // Integer
UserDefaults.standard.set("TEST", forKey: "KeyName") // setObject
// Retrieving values
UserDefaults.standard.bool(forKey: "KeyName")
UserDefaults.standard.integer(forKey: "KeyName")
UserDefaults.standard.string(forKey: "KeyName")
// Removing values
UserDefaults.standard.removeObject(forKey: "KeyName")