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

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


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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值