How to store custom objects in NSUserDefaults

后端 未结 7 1834
悲&欢浪女
悲&欢浪女 2020-11-21 11:48

Alright, so I\'ve been doing some poking around, and I realize my problem, but I don\'t know how to fix it. I have made a custom class to hold some data. I make objects fo

7条回答
  •  天命终不由人
    2020-11-21 12:00

    Swift 4 introduced the Codable protocol which does all the magic for these kinds of tasks. Just conform your custom struct/class to it:

    struct Player: Codable {
      let name: String
      let life: Double
    }
    

    And for storing in the Defaults you can use the PropertyListEncoder/Decoder:

    let player = Player(name: "Jim", life: 3.14)
    UserDefaults.standard.set(try! PropertyListEncoder().encode(player), forKey: kPlayerDefaultsKey)
    
    let storedObject: Data = UserDefaults.standard.object(forKey: kPlayerDefaultsKey) as! Data
    let storedPlayer: Player = try! PropertyListDecoder().decode(Player.self, from: storedObject)
    

    It will work like that for arrays and other container classes of such objects too:

    try! PropertyListDecoder().decode([Player].self, from: storedArray)
    

提交回复
热议问题