使用NSCoding保存结构

时间:2018-06-16 12:33:42

标签: swift struct nscoder

我想保存以下数据:

class Book: NSObject, NSCoding {

var title: String
var chapter: [Chapter]

struct Chapter {
    var chapTitle: String
    var texte: [Texte]
}

struct Texte {
    var description: String
    var texte: [String]
    var position: [Int]
    var hidden: [Int?]
}

我目前正在使用NSCoder保存Book类:

static let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
static let ArchiveURL = DocumentsDirectory.appendingPathComponent("learn")


struct PropertyKey {
    static let title = "title"
    static let chapter = "Chapter"
}

//MARK: - Initialization
init?(title: String, chapter: [Book.Chapter]) {        
    self.title = title
    self.chapter = chapter
}

//MARK: - NSCoding
func encode(with aCoder: NSCoder) {
    aCoder.encode(title, forKey: PropertyKey.title)
    aCoder.encode(chapter, forKey: PropertyKey.chapter)
}

required convenience init?(coder aDecoder: NSCoder) { 
    let title = aDecoder.decodeObject(forKey: PropertyKey.title) as! String
    let chapter = aDecoder.decodeObject(forKey: PropertyKey.chapter) as! [Book.Chapter]

    self.init(title: title, chapter: chapter)
}

有了这个,我可以保存本书的title和一个空数组chapter

但是当我尝试将chapTitletexte添加到Book对象时,我收到以下错误:

  

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:' - [ SwiftValue encodeWithCoder:]:无法识别的选择器发送到实例0x60000066dec0'

这是否意味着无法保存结构?我应该改变什么?

1 个答案:

答案 0 :(得分:0)

如果你能把书作为一个结构,你最好使用codable。

static func saveData (books: [Book]) throws
{
     let encoded = try JSONEncoder().encode(books)
     try encoded.write(to: ArchiveURL)
     print("Books saved")
}

保存

//retrive data from it's saved place
static func loadData() throws -> [Book]
{
     let data = try Data(contentsOf: ArchiveURL)
     return try JSONDecoder().decode([Book].self, from: data)
}

Retrive

let directory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] + "/learn/"

let ArchiveURL = URL(fileURLWithPath: directory)

同时编辑顶部的变量

jQuery("#media-uploader").dropzone({
    url: your_posting_url,
    acceptedFiles: 'image/jpeg',
    addedfile:function (file) {
        if( your condition ){
            // okay !
        } else {
            // not okay !
            this.removeFile(file);
        }
    },
    ... etc ...
});