UserDefaults是iOS中提供的一套最为基础的持久化方式,一般用于存储用户的基本信息
直接上代码:
// 最简单的使用于存取
func userDefaultsSave() -> Void {
let user:UserDefaults = UserDefaults.standard
/*基础的可存储的类型*/
set(URL(string: "https://www.baidu.com"), forKey: "url")
set("anyObject", forKey: "any")
set(true, forKey: "bool")
set(Double(10), forKey: "double")
set(Float(10), forKey: "float")
set(Int(10), forKey: "int")
/*数据读取*/
let url:URL = user.url(forKey: "url")!
let any:Any = user.object(forKey: "any")!
let bool:Bool = user.bool(forKey: "bool")
let double:Double = user.double(forKey: "double")
let float:Float = user.float(forKey: "float")
let int:Int = user.integer(forKey: "int")
print("url:\(url), any:\(any), bool:\(bool), double:\(double), float:\(float), int:\(int)")
/*存储数组*/
let array:Array<Any> = ["hello",["name":"bayMax"],["one","two","three"]]
set(array, forKey: "array")
/*存储字典*/
let dic:Dictionary<String,Any
"one":"hell0","two":["he","ll","ow"],
:["name":"zhangsan","age":"30"]]
set(dic, forKey: "dic")
let getArray:Array<Any> = user.object(forKey: "array") as! Array<Any>
let getDic:Dictionary<String,Any
object(forKey: "dic") as! Dictionary<String, Any>
print("array:\(getArray), dic:\(getDic)")
特点:swift中是不需要手动的去添加synchronize方法
UserDefaults 用于存储一些简单的数据,存储用户自定义数据时常常用到plist表格,并且对自定义数据进行归档与解归档操作
代码如下:
自定义数据
class CustomerModel:NSObject,NSCoding {
var name:String?
var age:Int?
var height:Float?
var ingoArray:Array<Any>?
var infoDic:Dictionary<String,Any>?
/*归档*/
func encode(with aCoder: NSCoder) {
encode(name, forKey: "name")
encode(age, forKey: "age")
encode(height, forKey: "height")
encode(ingoArray, forKey: "ingoArray")
encode(infoDic, forKey: "infoDic")
/*解归档*/
required init?(coder aDecoder: NSCoder) {
super.init()
name = aDecoder.decodeObject(forKey: "name") as? String
age = aDecoder.decodeObject(forKey: "age") as? Int
height = aDecoder.decodeObject(forKey: "height") as? Float
ingoArray = aDecoder.decodeObject(forKey: "ingoArray") as? Array<Any>
infoDic = aDecoder.decodeObject(forKey: "infoDic") as? Dictionary<String,Any>
/*初始化方法*/
override init() {
super.init()
/*使用数据*//*存储自定义对象*/
func saveCustomerData() -> Void {
let model:CustomerModel = CustomerModel.init()
name = "张三"
age = 30
height = 165.00
ingoArray = ["1","2","3"]
infoDic = ["one":"1","two":"2"]
/*存储到本地*/
accountPath=NSSearchPathForDirectoriesInDomains
documentDirectory, .userDomainMask, true).first!
"/userAccount.plist"
NSKeyedArchiver.archiveRootObject(model, toFile: accountPath)
let getmodel:CustomerModel = NSKeyedUnarchiver.unarchiveObject(withFile: accountPath) as! CustomerModel
print("getmodel:\(getmodel)")
一些简单的优化策略
针对于UserDefaults的存储策略
保证存储的一致性:在我们进行对去存储数据的操作过程中,往往返返的key值书写会为我们造成读取不成功的错误问题,为了避免这一问题使用全局的不可变key值去进行操作,保证了数据操作前后的一致性
分组存储策略:在进行存储过程中会遇到大量的相同key值,例如个人信息中含有id,展示数据中含有id,商品列表中含有ID,为了解决出现的不一致以及混乱问题我们可以把key值进行分组,以枚举的方式进行枚举所需要的key值
例如:
struct AccountInfoKey {
let userName = "userName"
let avatar = "avatar"
let password = "password"
let gender = "gender"
let age = "age"
// 登录信息
struct LoginInfoKey {
let token = "token"
let userId = "userId"
// 配置信息
struct SettingInfoKey {
let font = "font"
let backgroundImage = "backgroundImage"
上下文信息问题:这一问题为比如个人用户信心存储含有账号密码,登陆信息,个人配置信息等等,如果一点点的进行存储就会出现了读取不变的问题,使用结构体对零散信息进行整合,提高代理的逻辑性和清晰性
例如:
struct UserDefaultKeys {
// 账户信息
struct AccountInfo {
let userName = "userName"
let avatar = "avatar"
let password = "password"
let gender = "gender"
let age = "age"
// 登录信息
struct LoginInfo {
let token = "token"
let userId = "userId"
// 配置信息
struct SettingInfo {
let font = "font"
let backgroundImage = "backgroundImage"
不初始化进行访问属性:解决进行使用创建实例的麻烦:例如:(也可以是全局动态变量)
struct AccountInfo {
static let userName = "userName"
static let avatar = "avatar"
static let password = "password"
static let gender = "gender"
static let age = "age"
枚举分组存储(分组存储的优化)
struct UserDefaultKeys {
// 账户信息
enum AccountInfo: String {
case userName
case age
使用是直接用枚举的形式去系统的创建key值defaultStand.set("ChilliCheng",forKey: UserDefaultKeys.AccountInfo.userName.rawValue)