viewController
//
// ViewController.swift
// 06_NSUserDefaults
//
// Created by gaokunpeng on 16/7/4.
// Copyright © 2016年 apple. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
//NSUserDefaults的使用,NSUserDefaults使用的是单例对象
//1.获取
let btn = UIButton(type: .system)
btn.frame = CGRect(x: 100, y: 200, width: 100, height: 40)
btn.setTitle("获取", for: UIControlState())
btn.addTarget(self, action: #selector(clickBtn), for: .touchUpInside)
self.view.addSubview(btn)
btn.tag = 101
//2.存储
let saveBtn = UIButton(type: .system)
saveBtn.frame = CGRect(x: 100, y: 300, width: 100, height: 40)
saveBtn.setTitle("存储", for: UIControlState())
saveBtn.addTarget(self, action: #selector(saveAction), for: .touchUpInside)
self.view.addSubview(saveBtn)
//3.删除
let deleteBtn = UIButton(type: .system)
deleteBtn.frame = CGRect(x: 100, y: 400, width: 100, height: 40)
deleteBtn.setTitle("删除", for: UIControlState())
deleteBtn.addTarget(self, action: #selector(deleteAction), for: .touchUpInside)
self.view.addSubview(deleteBtn)
}
//存储
func saveAction(){
//NSUserDefaults适合存储轻量级的本地客户端数据,比如记住密码功能,要保存一个系统的用户名、密码。使用NSUserDefaults是首选。下次再登陆的时候就可以直接从NSUserDefaults里面读取上次登陆的信息。
//NSUserDefaults支持的数据格式也很多,有:Int,Float,Double,BOOL,甚至AnyObject类型。
//1、获取单例对象
let ud = UserDefaults.standard
//2、对原生数据类型的储存和读取
ud.set("张三", forKey: "name")
//存储字典
var person = [String:Any]()
person["name"] = "aixi"
ud.set(person, forKey: "PERSON")
//3,系统对象的存储与读取 UIImage
// 系统对象实现存储,需要通过archivedDataWithRootObject方法转换成NSData为载体,才可以存储。下面以UIImage对象为例:
let image = UIImage(named: "2")
let imageData:NSData = NSKeyedArchiver.archivedData(withRootObject: image ?? "3") as NSData
ud.set(imageData, forKey: "imageData")
// 自定义对象的存储和读取
// 如果想要存储自己定义的类,首先需要对该类实现NSCoding协议来进行归档和反归档(序列号和反序列化)。即该类内添加func encodeWithCoder(_encoder:NSCoder)方法和init(coder decoder:NSCoder)方法,并继承协议,然后将属性进行转换。
//自定义对象存储
let model = PersonModel(names: "WeiWei", ages: "18", weights: 100)
//实例对象转换成NSData
let modelData = NSKeyedArchiver.archivedData(withRootObject: model)
//存储NSData对象
ud.set(modelData, forKey: "modelData")
//使用扩展存储
ud.saveCustomObject(customObject: model, key: "extensionDuixiang")
//同步到文件
ud.synchronize()
/*
NSUserDefaults实现的原理
系统里面有一个文件来存储NSUserDefaults里面的数据
在程序启动的时候,系统将这个文件里面的所有数据读到内存里面
我们修改的数据只是修改了内存里面的数据
但是这个数据没有同步到文件里面,下一次使用的时候这个数据就没有
所以在程序结束之前我们都应该将内存里面的数据同步到文件
*/
}
//获取
func clickBtn(){
let ud = UserDefaults.standard
let name = ud.object(forKey: "name")
//获取字符串
if let tmpName = name {
print("获取字符串",tmpName)
let alert = UIAlertController(title: "温馨提示", message: "获取到值", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: {
print("提示弹出后调用打印函数")
})
}
//获取字典中的值
let person = ud.object(forKey: "PERSON")
if var perDict:Dictionary = person as? Dictionary<String, Any> {
print("获取字典中的值",perDict["name"]!)
}
//UIImage对象读取
//获取NSData
let objData = ud.object(forKey: "imageData")
if let imageData:NSData = objData as? NSData {
//还原对象
let myImage = NSKeyedUnarchiver.unarchiveObject(with: imageData as Data) as! UIImage
let btn:UIButton = self.view.viewWithTag(101) as! UIButton
btn.setBackgroundImage(myImage, for: .normal)
print("获取NSData",myImage)
}
//自定义对象读取
let modelData = ud.object(forKey: "modelData")
if let models = modelData {
let myModel = NSKeyedUnarchiver.unarchiveObject(with: models as! Data) as! PersonModel
print("自定义对象的值",myModel.name,myModel.age,myModel.weight)
}
//使用扩展获取
let extenModel = ud.getCustomObject(forKey: "extensionDuixiang")
if let dataModels:PersonModel = extenModel as? PersonModel {
print("扩展的user default==",dataModels.age)
}
}
//删除
func deleteAction(){
let ud = UserDefaults.standard
ud.removeObject(forKey: "name")
ud.removeObject(forKey: "PERSON")
ud.removeObject(forKey: "imageData")
ud.removeObject(forKey: "modelData")
ud.removeObject(forKey: "extensionDuixiang")
//同步
ud.synchronize()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
import Foundation
extension UserDefaults {
//用在登录的时候,存储用户名和密码,和相关全局信息
//存储
func saveCustomObject(customObject: NSCoding, key: String) {
let encodedObject = NSKeyedArchiver.archivedData(withRootObject: customObject)
self.set(encodedObject, forKey: key)
self.synchronize()
}
//获取
func getCustomObject(forKey key: String) -> AnyObject? {
let decodedObject = self.object(forKey: key) as? NSData
if let decoded = decodedObject {
let object = NSKeyedUnarchiver.unarchiveObject(with: decoded as Data)
return object as AnyObject
}
return nil
}
//移除
func removeCustomObject(key: String){
self.removeObject(forKey: key)
self.synchronize()
}
}
import UIKit
class PersonModel: NSObject,NSCoding {
var name:String
var age:String
var weight:Int
init(names:String,ages:String,weights:Int) {
self.name = names
self.age = ages
self.weight = weights
super.init()
}
//当我们在子类定义了指定初始化器(包括自定义和重写父类指定初始化器),那么必须显示实现required init?(coder aDecoder: NSCoder),而其他情况下则会隐式继承,我们可以不用理会。
//提供一个解码器解码数据,通过解码数据来初始化类变量
// MARK:- 处理需要解档的字段
required init(coder aDecoder:NSCoder){
self.name = aDecoder.decodeObject(forKey: "name") as! String
self.age = aDecoder.decodeObject(forKey: "age") as! String
self.weight = Int(aDecoder.decodeInt32(forKey: "weight"))
}
//提供一个编码器编码数据
// MARK:- 处理需要归档的字段
func encode(with aCoder: NSCoder) {
aCoder.encode(name,forKey:"name")
aCoder.encode(age,forKey:"age")
aCoder.encode(weight,forKey:"weight")
}
}