ios - 如何在Swift 3中使用持久化并检索与NSCoding兼容的对象到app文档目录?

标签 ios nsfilemanager nscoding

这是一个符合NSCoding的对象。我想从Swift 3的应用程序文档目录中保存和恢复它。我想这是一种保存方法和恢复方法。怎么做?

import Foundation

class Book: NSObject, NSCoding {
    var title: String
    var author: String
    var pageCount: Int
    var categories: [String]
    var available: Bool

    init(title:String, author: String, pageCount:Int, categories:[String],available:Bool) {
        self.title = title
        self.author = author
        self.pageCount = pageCount
        self.categories = categories
        self.available = available
    }

    // MARK: NSCoding
    required convenience init?(coder: NSCoder) {

        let title = coder.decodeObject(forKey: "title") as! String
        let author = coder.decodeObject(forKey: "author")as! String
        let categories = coder.decodeObject(forKey: "categories") as! [String]
        let available = coder.decodeBool(forKey: "available")
        let pageCount = coder.decodeInteger(forKey: "pageCount")

        self.init(title:title, author:author,pageCount:pageCount,categories: categories,available:available)
    }

    func encode(with: NSCoder) {
        with.encode(self.title, forKey: "title")
        with.encode(self.author, forKey: "author")
        with.encode(Int32(self.pageCount), forKey: "pageCount")
        with.encode(self.categories, forKey: "categories")
        with.encode(self.available, forKey: "available")
    }
}

谢谢!

最佳答案

保存:

// Get documents directory
if let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {

    // Append your file name to the directory path
    let path = (docs as NSString).appendingPathComponent("filename")

    // Archive your object to a file at that path
    NSKeyedArchiver.archiveRootObject(yourObject, toFile: path)
}

正在加载:
// Get documents directory
if let docs = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first {

    // Append your file name to the directory path
    let path = (docs as NSString).appendingPathComponent("filename")

    // Unarchive your object from the file
    let yourObject = NSKeyedUnarchiver.unarchiveObject(withFile: path) as? Book

    // do whatever with yourObject
}

关于ios - 如何在Swift 3中使用持久化并检索与NSCoding兼容的对象到app文档目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38666015/

相关文章:

ios - 从集合中删除对象会使 CoreData 中的逆关系无效

ios - GPUImageMovieWriter - 录制视频两端偶尔出现黑帧

ios - 检索 JSON 对象并填充数组 Swift

ios - 在 swift 中使用编码器时是否保留了节点父子关系?

IOS - UICollectionView - 通过 segue 将数据传递给 subview

objective-c - 访问存储在 iOS 设备上的文本文件

objective-c - NSFileManager fileExistsAtPath:isDirectory的用法

ios - fileManager.createFileAtPath 总是失败

swift - 将具有 String 和 NSImage 属性的类导出到文件

ios - 如何将 NSCoding 协议(protocol)与枚举一起使用?