码迷,mamicode.com
首页 > 编程语言 > 详细

SWIFT中将信息保存到plist文件内

时间:2015-07-18 22:36:38      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

在项目中可能我们需要保存一些数据到plist文件中,以下就本人在学习过程中的笔记,不成熟的地方请指出。

可能我有一个类叫做Student

import UIKit

class Student: NSObject {
    var text:String
    var age:Bool
    init(text:String,age:Int) {
        self.text = text
        self.age = age
    }
    
    //从nsobject中解析回来
    init(coder aDecoder:NSCoder){
        self.text = aDecoder.decodeObjectForKey("Text") as! String
        self.age = aDecoder.decodeObjectForKey("Age") as! Int
    }
    
    //编码成object
    func encodeWithCoder(aCoder:NSCoder){
        aCoder.encodeObject(text, forKey: "Text")
        aCoder.encodeObject(checked, forKey: "Age")
    }
    
}

 encodeWithCoder方法中,每一个属性设置为一个关键字,用于序列化编码,以便我们在init(coder aDecoder:NSCoder)中解析回来

以下是两个保存用加载plist数据的方法

var students:[Student] = [Student]()
func loadStudentsData() {
        let path = self.dataFilePath()
        //声明文件管理器
        let defaultManager = NSFileManager()
        if defaultManager.fileExistsAtPath(path) {
            let data = NSData(contentsOfFile: path)
            //解码器
            let archive = NSKeyedUnarchiver(forReadingWithData: data!)
            students = archive.decodeObjectForKey("Students") as! Array
            //结束解码
            archive.finishDecoding()
        } else {
          saveStudentsData()
        }
    }
    
    func saveStudentsData() {
        var data = NSMutableData()
        //聲明一個歸檔處理對象
        var archive = NSKeyedArchiver(forWritingWithMutableData: data)
        //將arrData進行編碼
        archive.encodeObject(students, forKey: "Students")
        archive.finishEncoding()
        //數據寫入
        data.writeToFile(dataFilePath(), atomically: true)
    }

 在UI启动的时候加入loadStudentsData()方法,每次有改变students数组的时候调用saveStudentsData()方法

SWIFT中将信息保存到plist文件内

标签:

原文地址:http://www.cnblogs.com/foxting/p/4657771.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!