如何使用NSCoding swift

时间:2016-10-13 14:30:03

标签: ios swift dictionary nscoding

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

目前在Course.swift中我有NSCoding设置。我的程序写入并读取所有课程信息。但现在我想改变它,以便它写这个字典而不是所有的课程。我没有另一个包含这个字典的数据类,它只是保存在我的“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放入我的View Controller中?

class StartUpViewController: UIViewController {

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

...
}

1 个答案:

答案 0 :(得分:2)

创建符合NSCoding的新类。

这个新类有一个属性:

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]
    }

将NSCoding协议实现保留在Course类中,因为它将在编码字典时使用。