如何使用 NSCoding swift 存储自定义对象数组的字典

How to store a dictionary of arrays of custom objects using NSCoding swift

所以我遇到了问题。我正在制作此应用程序,该应用程序当前存储 "Courses" 的信息。但是,我一直在多次更改应用程序,现在我想要一本课程词典。我需要能够保存这本课程词典并从任何 class 加载它。

目前在 Course.swift 我有 NSCoding 设置。我的程序写入和读取所有课程信息。但现在我想改变它,让它写这本词典而不是所有课程。我没有保存这本字典的其他数据 class,它只是保存在我的 "StartUpViewController.swift" 中。

class Course: NSObject, NSCoding {

// MARK: Properties
var courseName : String
var projects : [String]
var projectMarks : [Double]
var projectOutOf : [Double]
var projectWeights : [Double]

// MARK: Archiving Paths

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

struct PropertyKey {
    static let courseNameKey = "courseName"
    static let projectsKey = "projects"
    static let projectMarksKey = "projectMarks"
    static let projectOutOfKey = "projectOutOf"
    static let projectWeightsKey = "projectWeights"
}

// MARK: NSCoding

func encode(with aCoder: NSCoder) {
    aCoder.encode(courseName, forKey: PropertyKey.courseNameKey)
    aCoder.encode(projects, forKey: PropertyKey.projectsKey)
    aCoder.encode(projectMarks, forKey: PropertyKey.projectMarksKey)
    aCoder.encode(projectOutOf, forKey: PropertyKey.projectOutOfKey)
    aCoder.encode(projectWeights, forKey: PropertyKey.projectWeightsKey)
}

required convenience init?(coder aDecoder: NSCoder) {
    let courseName = aDecoder.decodeObject(forKey: PropertyKey.courseNameKey) as! String
    let projects = aDecoder.decodeObject(forKey: PropertyKey.projectsKey) as! [String]
    let projectMarks = aDecoder.decodeObject(forKey: PropertyKey.projectMarksKey) as! [Double]
    let projectOutOf = aDecoder.decodeObject(forKey: PropertyKey.projectOutOfKey) as! [Double]
    let projectWeights = aDecoder.decodeObject(forKey: PropertyKey.projectWeightsKey) as! [Double]

    self.init(courseName: courseName, projects: projects, projectMarks: projectMarks, projectOutOf: projectOutOf, projectWeights: projectWeights)
}

我该怎么做?我是使用 NSCoding 保留 Course.swift,还是只需要将 NSCoding 放在我的视图控制器中?

class StartUpViewController: UIViewController {

var groups: [String: [Course]?] = [:]

...
}

创建一个新的 class 符合 NSCoding。

这个新 class 有一个 属性 :

var courses: [String : Course]?

以及方法:

func encode(with aCoder: NSCoder) {
    if let courses = courses {
        aCoder.encode(courses, forKey: "courses")
    }
}

required convenience init?(coder aDecoder: NSCoder) { 
    courses = aDecoder.decodeObject(forKey: "courses") as? [String : Course]
    }

并在课程 class 中保留您的 NSCoding 协议实现,因为它将在对字典进行编码时使用。