项目中遇到需要存储的数据目前有四种方式,偏好设置(UserDefaults),文件存储,SQLite,CoreData,第一种方式比较简单,第二种方式一般使用归档和解档的方式实现,先来简单了解一下App基本目录:
偏好设置
偏好设置比较简单,设置数据取数据,代码如下:
let defaults:UserDefaults = UserDefaults.standard
defaults.setValue("FlyElephant", forKeyPath: "userName")
设置的数据最终保存在Plist文件中:
归档和解档
自定义对象存储需要实现NSCoding协议中的encode和decode方法:
public protocol NSCoding {
public func encode(with aCoder: NSCoder)
public init?(coder aDecoder: NSCoder) // NS_DESIGNATED_INITIALIZER
}
自定义归档的Order对象:
class Order:NSObject,NSCoding {
var orderName:String = ""
var userName:String = ""
init(orderName:String, userName:String) {
self.orderName = orderName
self.userName = userName
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init()
self.orderName = aDecoder.decodeObject(forKey: "OrderName") as! String
self.userName = aDecoder.decodeObject(forKey: "UserName") as! String
}
func encode(with aCoder: NSCoder) {
aCoder.encode(self.orderName, forKey:"OrderName")
aCoder.encode(self.userName, forKey: "UserName")
}
}
归档操作:
@IBAction func archiverAction(_ sender: UIButton) {
let order:Order = Order(orderName: "123456789", userName: "FlyElephant")
NSKeyedArchiver.archiveRootObject(order, toFile: getSavePath())
}
解档操作:
@IBAction func unArchiverAction(_ sender: UIButton) {
let order:Order = NSKeyedUnarchiver.unarchiveObject(withFile: getSavePath()) as! Order
print("订单的名称:\(order.orderName)---用户名称--\(order.userName)")
}
存储路径:
private func getSavePath()->String {
let cacheDir:String = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let localPath:String = cacheDir.appending("TempTest.plist")
return localPath;
}
保存数据: