Reputation: 757
I am created 3 object and save each of this inside user defaults how I am can update not all data, are only object Number 3?
This is code how I am save and fetch data:
func savePlayer(player: [Player]) {
UserDefaults.standard.set(try? PropertyListEncoder().encode(player), forKey:"player")
UserDefaults.standard.synchronize()
}
func getSports() -> [Player]? {
if let data = UserDefaults.standard.value(forKey:"player") as? Data {
let decodedSports = try? PropertyListDecoder().decode([Player].self, from: data)
return decodedSports
}
return nil
}
This is my objects:
let playerOne = Player(id: 1, url: "https:\\www.google - 1.com", color: "#color 1", image: "imageBase64One", flag: false, position: 1)
let playerTwo = Player(id: 2, url: "https:\\www.google - 2.com", color: "#color 2", image: "imageBase64Two", flag: false, position: 2)
let playerThree = Player(id: 3, url: "https:\\www.google - 3.com", color: "#color 3", image: "imageBase64Three", flag: false, position: 3)
Model of data:
class Player: Codable {
let ID: Int
let URL: String
let Color: String
let Image: String
var Flag: Bool
let Position: Int
init(id: Int, url: String, color: String, image: String, flag: Bool, position: Int) {
self.ID = id
self.URL = url
self.Color = color
self.Image = image
self.Flag = flag
self.Position = position
}
}
I can't understand how update for example option "flag" for second object and and also delete only object two not all.
Upvotes: 1
Views: 670
Reputation: 843
There's no need to set in your class the position of each item and no need to call UserDefaults.standard.synchronize() either since it's deprecated.
Anyway, whenever you want to edit an object from your array:
var myArray: [Player] = []!
myArray[2] = Player(id: 15, url: "https:\\www.niceUrl.com", color: .black, image: "niceImage", flag: true, position: 2)
savePlayer(player: myArray[2])
Note that here I changed all of the values, if you just want to change one you can.
Upvotes: 1