使用NSCoding Swift保存对象时出现异常

时间:2017-09-23 18:14:36

标签: ios swift xcode nscoding

尝试使用NSCoding保存/存档对象时遇到了一些问题。我基本上有一个定义问题和答案的类QA,我还有一个类Volume,它包含几个属性,包括一个QA对象数组。

调用NSKeyedArchiver.archiveRootObject方法时发生错误。我怀疑是它与QA对象的数组有关,因为如果我注释掉那部分,则不会抛出异常。

My Volume类继承自NSObject和NSCoding,而QA对象仅从NSObject继承。

  

抛出的异常是:... encodeWithCoder:]:无法识别的选择器   发送到实例0x600000077c80

用于存档的方法是:

static func save() {
    print("starting save...")
    let DocumentsDirectory = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first!
    let ArchiveURL = DocumentsDirectory.appendingPathComponent("volumesData")
    NSKeyedArchiver.archiveRootObject(VolumeTableViewController.volumesArray, toFile: ArchiveURL.path)
    print("Ending save...")
}

我的卷类是:

import Foundation
class Volume: NSObject, NSCoding {
    let volumeNumber: Int
    var completed: Bool
    var questionsData: [QA]

    init (volumeNumber: Int, completed: Bool, questionsData: [QA]) {
        self.volumeNumber = volumeNumber
        self.completed = completed
        self.questionsData = questionsData
    }

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

        let volumeNumber = aDecoder.decodeObject(forKey: "volumeNumber") as! Int
        let completed = aDecoder.decodeObject(forKey: "completed") as! Bool
        let questionsData = aDecoder.decodeObject(forKey: "questionsData") as! [QA]

        self.init(volumeNumber: volumeNumber, completed: completed, questionsData: questionsData)
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(volumeNumber, forKey: "volumeNumber")
        aCoder.encode(completed, forKey: "completed")
        aCoder.encode(questionsData, forKey: "questionsData")
    }
}

我的QA课程是:

 import Foundation
class QA: NSObject {
    let questionsText: String
    let answerText: [String]
    let correctAnswer: [Bool]
    var selectedAnswer: [Bool?]


    // Create standard initiator
    init(questionsText:String, answerText: [String], correctAnswer: [Bool], selectedAnswer: [Bool?]) {
        self.questionsText = questionsText
        self.answerText = answerText
        self.correctAnswer = correctAnswer
        self.selectedAnswer = selectedAnswer
    }
} 

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

QA也应该采用NSCoding。根据规则,对象的自定义属性应该是可存档的,对象的对象图中的每个对象也符合NSCoding。

对Swift 4使用Codable协议。