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

本文介绍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)
    }
}
//全局变量Key
struct 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

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...