Swift-->NSKeyedArchiver与NSKeyedUnarchiver数据存档读取(文件)

来源:互联网 发布:js当前时间加一小时 编辑:程序博客网 时间:2024/06/05 03:26

本文介绍Swift2.2 中, 创建文件/文件夹, 将NSObject对象存档到文件, 并从存档文件读取对象.

1:可存档对象声明

//必须要继承NSObject对象,并且实现NSCoding协议class DataBean: NSObject, NSCoding {    var image: UIImage?    var name: String    var rate: Int    init?(name: String, rate: Int, image: UIImage?) {        self.image = image        self.rate = rate        self.name = name        super.init()//注意        if name.isEmpty || rate < 0 {            return nil        }    }    //必须实现的构造方法    required convenience init?(coder aDecoder: NSCoder) {        //decode操作        let image = aDecoder.decodeObjectForKey(DataKey.imageKey) as! UIImage        let name = aDecoder.decodeObjectForKey(DataKey.nameKey) as! String        let rate = aDecoder.decodeIntegerForKey(DataKey.rateKey)        self.init(name: name, rate: rate, image: image)    }    //必须实现的encode方法    func encodeWithCoder(aCoder: NSCoder) {        aCoder.encodeObject(image, forKey: DataKey.imageKey)        aCoder.encodeObject(name, forKey: DataKey.nameKey)        aCoder.encodeInteger(rate, forKey: DataKey.rateKey)    }}//全局变量Keystruct DataKey {    static let imageKey = "image"    static let nameKey = "name"    static let rateKey = "rate"}

2:存档路径的选择

//文件存档的文件夹, 类似: /Users/angcyo/Library 这样的路径static var DocumentDirectory: NSURL {    //文件管理对象    let fileManager = NSFileManager.defaultManager()    //获取DocumentationDirectory对应的文件夹, 类似/Users/angcyo/Library/Documentation/ 这样的    //当然,你可以创建自定义的文件夹,或者其他文件夹路径...详情参考API文档说明.    let docPath = fileManager.URLsForDirectory(.DocumentationDirectory, inDomains: .UserDomainMask).first!    //如果文件夹不存在,肯定是不行的. 所以...判断一下.    if !fileManager.fileExistsAtPath(docPath.path!) {        //创建文件夹...        try! fileManager.createDirectoryAtPath(docPath.path!, withIntermediateDirectories: true, attributes: nil)    }    return docPath    }//文件存档的文件名 (全路径), 文件允许不存在,但是文件所在的文件夹,一定要存在,否则会保存失败.static let DataPathUrl = DocumentDirectory.URLByAppendingPathComponent("data_bean_s")

3:对象的写入和读取

//数据数组var datas = [DataBean]()// MARK: 保存func saveDataToFile() {    let isSuccessSave = NSKeyedArchiver.archiveRootObject(datas, toFile: DataBean.DataPathUrl.path!)    if isSuccessSave {        print("数据保存成功:\(DataBean.DataPathUrl.path!)")    } else {        print("数据保存失败:\(DataBean.DataPathUrl.path!)")    }}// MARK: 读取func loadDataFromFile() -> [DataBean]? {    return NSKeyedUnarchiver.unarchiveObjectWithFile(DataBean.DataPathUrl.path!) as? [DataBean]}

源代码: https://github.com/angcyo/TableViewDemo/tree/NSKeyedArchiver

其他存储方式参考: http://blog.csdn.net/angcyo/article/details/52347524


至此: 文章就结束了,如有疑问: QQ群 Android:274306954 Swift:399799363 欢迎您的加入.

0 0
原创粉丝点击