How to archive and unarchive custom objects in Swift? Or how to save custom object to NSUserDefaults in Swift?

后端 未结 5 1251
梦毁少年i
梦毁少年i 2020-12-10 02:46

I have a class

class Player {

    var name = \"\"

    func encodeWithCoder(encoder: NSCoder) {
        encoder.encodeObject(name)
    }

    func initWith         


        
5条回答
  •  情深已故
    2020-12-10 02:49

    I have a class

        class Player {
            var name = ""
            init(name: String) {
                self.name = name
            }
        }
    

    and i want to serialise it and save to user defaults.

    In Swift 4 / iOS 11, there's a whole new way to do this. It has the advantage that any Swift object can use it — not just classes, but also structs and enums.

    You'll notice that I've omitted your NSCoding-related methods, because you won't need them for this purpose. You can adopt NSCoding here, as you know; but you don't have to. (And a struct or enum cannot adopt NSCoding at all.)

    You start by declaring your class as adopting the Codable protocol:

    class Player : Codable {
        var name = ""
        init(name: String) {
            self.name = name
        }
    }
    

    It then becomes a simple matter to serialize it into a Data object (NSData) which can be stored in UserDefaults. The very simplest way is to use a property list as an intermediary:

    let player = Player(name:"matt")
    try? UserDefaults.standard.set(PropertyListEncoder().encode(player), 
        forKey:"player")
    

    If you use that approach, let's now prove that you can pull the same Player back out of UserDefaults:

    if let data = UserDefaults.standard.object(forKey:"player") as? Data {
        if let p = try? PropertyListDecoder().decode(Player.self, from: data) {
            print(p.name) // "matt"
        }
    }
    

    If you'd rather pass through an NSKeyedArchiver / NSKeyedUnarchiver, you can do that instead. Indeed, there are some situations where you'll have to do so: you'll be presented with an NSCoder, and you'll need to encode your Codable object inside it. In a recent beta, Xcode 9 introduced a way to do that too. For example, if you're encoding, you cast the NSCoder down to an NSKeyedArchiver and call encodeEncodable.

提交回复
热议问题