UserDefaults 支持的数据格式也很多,有:Int,Float,Double,BOOL,Array,Dictionary,甚至 Any 类型。
let user = UserDefaults.standard
//Any
user.set("wc", forKey: "value")
let value:Any? = user.object(forKey: "value")
print("value==============\(value)")
//Int
user.set(1234, forKey: "IntValue")
let intValue:Int = user.integer(forKey: "IntValue")
print("intValue==============\(intValue)")
//Float
user.set(12.33, forKey: "FloatValue")
let floatValue:Float = user.float(forKey: "FloatValue")
print("floatValue=============\(floatValue)")
//Double
user.set(1.234, forKey: "DoubleValue")
let doubleValue:Double = user.double(forKey: "DoubleValue")
print("doubleValue==============\(doubleValue)")
//Bool
user.set(true, forKey: "BoolValue")
let boolValue:Bool = user.bool(forKey: "BoolValue")
print("boolValue===============\(boolValue)")
//Url
let url1:URL = URL(string: "https://www.baidu.com")!
user.set(url1, forKey: "URLValue")
let urlValue:URL = user.url(forKey: "URLValue")!
print("urlValue===============\(urlValue)")
//String
user.set("123", forKey: "StringValue")
let stringValue:String = user.string(forKey: "StringValue")!
print("stringValue============\(stringValue)")
//NSNumber
var number = NSNumber(value:22)
user.set(number, forKey: "NSNumber")
number = user.object(forKey: "NSNumber") as! NSNumber
print("number=-=========\(number)")
//Array类型
var array:Array = ["123","456"]
user.set(array, forKey: "Array")
array = user.array(forKey: "Array") as! [String]
//Dictionary类型
var dictionary = ["1":"hangge.com"]
user.set(dictionary, forKey: "Dictionary")
dictionary = user.dictionary(forKey: "Dictionary") as! [String : String]
//系统对象实现存储,需要通过 archivedData 方法转换成 Data 为载体,才可以存储。
//UILabel对象存储
//将对象转换成Data流
let label = UILabel()
label.text = "欢迎访问hangge.com"
let labelData = NSKeyedArchiver.archivedData(withRootObject: label)
//存储Data对象
user.set(labelData, forKey: "labelData")
//UILabel对象读取
//获取Data
let objData = user.data(forKey: "labelData")
//还原对象
let myLabel = NSKeyedUnarchiver.unarchiveObject(with: objData!) as? UILabel
print(myLabel as Any)
//如果我们过直接把 image1 存储起来,再取出转换回 UIImage 就变成了 nil。必须先转成 image2 再存储。
//UIImage对象存储
//将对象转换成Data流
let image1 = UIImage(named: "apple.png")!
let image2 = UIImage(cgImage: image1.cgImage!, scale: image1.scale,
orientation: image1.imageOrientation)
let imageData = NSKeyedArchiver.archivedData(withRootObject: image2)
//存储Data对象
user.set(imageData, forKey: "imageData")
//UIImage对象读取
//获取Data
let iiiimg = user.data(forKey: "imageData")
//还原对象
let myImage = NSKeyedUnarchiver.unarchiveObject(with: iiiimg!) as? UIImage
print(myImage)
如果想要存储自己定义的类,首先需要对该类实现 NSCoding 协议来进行归档和反归档(序列化和反序列化)。即该类内添加 func encode(with coder: NSCoder) 方法和 init(coder decoder: NSCoder) 方法,将属性进行转换。