微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 欢迎您的加入.

原文地址:https://www.jb51.cc/swift/323184.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐