一. UserDefaults 常用使用场景
- 存储用户偏好设置
- 存储缓存信息
- 轻量级数据存储
UserDefaults会在本地存储数据,使得程序进程结束后,仍能保留数据,在下次进入App后,这些数据可以被使用。
二. 默认支持存储的数据类型
NSArray NSData NSDate NsDictionary NsString NSNumber(Bool Integer Float Double)
三. 使用方法
1.添加(set)
//获取UserDefaults实例
let userDefaults = UserDefaults.standard
userDefaults.set(123, forKey: "defaultKey")
//将存储的偏好存储同步到ROM中
userDefaults.synchronize()
- 读取
var readInt = userDefaults.integer(forKey: "defaultKey")
修改
通过key值直接set覆盖即可删除
userDefaults.removeObject(forKey: "defaultKey")
//删除所有
//获取应用域的所有字符串
let appDomainString = Bundle.main.bundleIdentifier
userDefaults.removePersistentDomain(forName: appDomainString)
原生数据的存储:
let userDefault = UserDefaults.standard
//Any
userDefault.set("hangge.com", forKey: "Object")
let objectValue:Any? = userDefault.object(forKey: "Object")
//Int类型
userDefault.set(12345, forKey: "Int")
let intValue = userDefault.integer(forKey: "Int")
//Float类型
userDefault.set(3.2, forKey: "Float")
let floatValue = userDefault.float(forKey: "Float")
//Double类型
userDefault.set(5.2240, forKey: "Double")
let doubleValue = userDefault.double(forKey: "Double")
//Bool类型
userDefault.set(true, forKey: "Bool")
let boolValue = userDefault.bool(forKey: "Bool")
//URL类型
userDefault.set(URL(string:"http://hangge.com")!, forKey: "URL")
let urlValue = userDefault.url(forKey: "URL")
//String类型
userDefault.set("hangge.com", forKey: "String")
let stringValue = userDefault.string(forKey: "String")
//NSNumber类型
var number = NSNumber(value:22)
userDefault.set(number, forKey: "NSNumber")
number = userDefault.object(forKey: "NSNumber") as! NSNumber
//Array类型
var array:Array = ["123","456"]
userDefault.set(array, forKey: "Array")
array = userDefault.array(forKey: "Array") as! [String]
//Dictionary类型
var dictionary = ["1":"hangge.com"]
userDefault.set(dictionary, forKey: "Dictionary")
dictionary = userDefault.dictionary(forKey: "Dictionary") as! [String : String]
四. 对自定义数据的存储
let userDefault = UserDefaults.standard
//自定义对象存储
let model = UserInfo(name: "航歌", phone: "3525")
//实例对象转换成Data
let modelData = NSKeyedArchiver.archivedData(withRootObject: model)
//存储Data对象
userDefault.set(modelData, forKey: "myModel")
//自定义对象读取
let myModelData = userDefault.data(forKey: "myModel")
let myModel = NSKeyedUnarchiver.unarchiveObject(with: myModelData!) as! UserInfo
print(myModel)
//----- 自定义对象类 -----
class UserInfo: NSObject, NSCoding {
var name:String
var phone:String
//构造方法
required init(name:String="", phone:String="") {
self.name = name
self.phone = phone
}
//从object解析回来
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "Name") as? String ?? ""
self.phone = decoder.decodeObject(forKey: "Phone") as? String ?? ""
}
//编码成object
func encode(with coder: NSCoder) {
coder.encode(name, forKey:"Name")
coder.encode(phone, forKey:"Phone")
}
}