本文介绍了如何使用persist&检索符合NSCoding的对象到Swift 3中的应用程序文档目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here's a NSCoding compliant object. I would like to save and recover it from the app's documents directory in Swift 3. I imagine it's a save method and recover method. How is this done?

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
}

这篇关于如何使用persist&检索符合NSCoding的对象到Swift 3中的应用程序文档目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 00:53