Right now I have a struct
with multiple dictionaries and string that holds the user's score for each level and the user's name that they type. I then save the struct
scores into an NSUserdefault
.
struct Scores: Codable {
var userName: String = ""
var totalScore: Int = 0
var highScore: [String : Int] = [:]
var scoreA: [String : Int] = [:]
var scoreB: [String : Int] = [:]
}
UserDefaults.standard.set(try? PropertyListEncoder().encode(scores), forKey:"scores_1")
This works well but I will need to save the user's last ten scores. I am wondering if I should use core-data
or keep using NSUserdefaults
? Not sure which is best practice.
Edit: Should I save the data in a .json file?
UserDefaults is best used to store small amounts of data, and not arrays.
Every time you call the key, the entire plist file that it's stored in is called into memory.
eg)
let volumeLevel = UserDefaults.Standard.integer(forKey: "volume")
So if you are storing an array that grows every time the user plays, eventually you will have memory problems.
With the example you have above, using UserDefaults to store High Score and UserName is fine, but I would recommend using CoreData (or something else) to store an array that has data for each run of the game.