swift 使用UserDefaults保存数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 使用UserDefaults保存数据相关的知识,希望对你有一定的参考价值。

# 1. With custom objects

Actually, you will need to archive the custom object into NSData then save it to user defaults and retrieve it from user defaults and unarchive it again. You can archive it like this
```
let teams = [Team(id: 1, name: "team1", shortname: "t1"), Team(id: 2, name: "team2", shortname: "t2")]

var userDefaults = UserDefaults.standard
let encodedData: Data = NSKeyedArchiver.archivedData(withRootObject: teams)
userDefaults.set(encodedData, forKey: "teams")
userDefaults.synchronize()
```

and unarchive it like this
```
let decoded  = userDefaults.object(forKey: "teams") as! Data
let decodedTeams = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Team]
```

But if you just did that you will get
`.Team encodeWithCoder:]: unrecognized selector sent to instance`

You will have to make Team conform to NSCoding just like this
```
class Team: NSObject, NSCoding {
    var id: Int
    var name: String
    var shortname: String


    init(id: Int, name: String, shortname: String) {
        self.id = id
        self.name = name
        self.shortname = shortname

    }

    required convenience init(coder aDecoder: NSCoder) {
        let id = aDecoder.decodeInteger(forKey: "id")
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let shortname = aDecoder.decodeObject(forKey: "shortname") as! String
        self.init(id: id, name: name, shortname: shortname)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(id, forKey: "id")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(shortname, forKey: "shortname")
    }
}
```

*@see: http://stackoverflow.com/questions/29986957/save-custom-objects-into-nsuserdefaults*
let myVar = "myValue"
let userDefaults = UserDefaults.standard

// Saving
userDefaults.set(myVar, forKey: "myVar")
userDefaults.synchronize()

// Retriving
if let myVar = userDefaults.value(forKey: "myVar") {
        //do something here when myVar exists
    } else {
        //myVar not exists
}

以上是关于swift 使用UserDefaults保存数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 userDefaults 保存打印数组(swift 3)

Swift:无法将数组保存到 UserDefaults

swift 在UserDefaults中保存自定义类

Swift: 用UserDefaults保存复杂对象

Swift:如何检查 UserDefaults 是不是存在,如果不保存选择的标准值?

Swift 5 将 AVAsset 保存到 UserDefaults