本地数据的保存与加载(使用NSCoder将对象保存到.plist文件)

import UIKit

class UserInfo: NSObject,NSCoding {

    var name:String
    var phone:String 
    
    //
    required init(username:String,userphone:String) {
        self.name = username
        self.phone = userphone
    }
    
    //解码
    required init?(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "Name") as! String
        self.phone = aDecoder.decodeObject(forKey: "Phone") as! String
    }
    //编码
    func encode(with aCoder: NSCoder) {
        aCoder.encode(name, forKey:"Name")
        aCoder.encode(phone, forKey: "Phone")
    }
    
}
import UIKit

class DataModel: NSObject {
    var userList = [UserInfo]()
    
    override init() {
        super.init()
        print("沙盒文件夹路径:\(documentsDirectory())")
        print("数据文件路径:\(dataFilePath())")
    }
    
    //
    func saveData()  {
        let data = NSMutableData()
        //申明一个归档处理对象
        let archiver = NSKeyedArchiver(forWritingWith: data)
        //将lists以对应Checklist关键字进行编码
        archiver.encode(userList, forKey: "userlist")
        //编码结束
        archiver.finishEncoding()
        //数据写入
        data.write(toFile: dataFilePath(), atomically: true)

    }
    //读取数据
    func loadData() {
        //获取本地数据文件地址
        let path = self.dataFilePath()
        //声明文件管理器
        let defaultManager = FileManager()
        //通过文件地址判断数据文件是否存在
        if defaultManager.fileExists(atPath: path) {
            //读取文件数据
            let url = URL(fileURLWithPath: path)
            let data = try! Data(contentsOf: url)
            //解码器
            let unarchiver = NSKeyedUnarchiver(forReadingWith: data)
            //通过归档时设置的关键字Checklist还原lists
            userList = unarchiver.decodeObject(forKey: "userlist") as! Array
            //结束解码
            unarchiver.finishDecoding()
        }
    }
    
    //获取沙盒文件夹路径
    func documentsDirectory() -> String {
        let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory,
                                                        .userDomainMask, true)
        let documentsDirectory = paths.first!
        return documentsDirectory
    }
    
    //获取数据文件地址
    func dataFilePath ()->String{
        return self.documentsDirectory().appendingFormat("/userList.plist")
    }
    
}
import UIKit

class FirstViewController: UIViewController {

     var dataModel:DataModel = DataModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        creat()
        // Do any additional setup after loading the view.
    }
    func creat()  {
        dataModel.userList.append(UserInfo(username: "小明1", userphone: "1234"))
        dataModel.userList.append(UserInfo(username: "小明2", userphone: "2234"))
        dataModel.userList.append(UserInfo(username: "小明3", userphone: "3234"))
    }
    
    

    @IBAction func saveBtn(_ sender: Any) {
        dataModel.saveData()
        print("保存成功!")
    }
    @IBAction func getBtn(_ sender: Any) {
        dataModel.loadData()
        print("读取成功!", dataModel.userList)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

你可能感兴趣的:(本地数据的保存与加载(使用NSCoder将对象保存到.plist文件))