在具有枚举数组作为属性的自定义类上使用NSCoding

时间:2015-11-10 17:17:30

标签: swift enums swift2 nscoding

我正在尝试能够序列化和解码自定义类。类本身有一个属性,它是一个枚举数组,如下所示:

(我已经阅读了如何使用原始值并序列化,但我没有运气,想弄清楚如何使用这样的数组)。

enum WeekDays : String {

case Sunday     = "Sunday"
case Monday     = "Monday"
case Tuesday    = "Tuesday"
case Wednesday  = "Wednesday"
case Thursday   = "Thursday"
case Friday     = "Friday"
case Saturday   = "Saturday"
}

class User: NSObject, NSCoding {

var name     : String
var workDays : [WeekDays]

init(name: String, workDays: [WeekDays]) {

    self.name = name
    self.workDays = workDays
}

required init(coder aDecoder: NSCoder) {

    self.name = aDecoder.decodeObjectForKey("name") as! String
    //        self.workDays =  ???? 
}

func encodeWithCoder(aCoder: NSCoder) {

    aCoder.encodeObject(self.name, forKey: "name")
//        aCoder.encodeObject(self.workDays, forKey: "workDays") 
}

}

1 个答案:

答案 0 :(得分:1)

如何按照Matt Neuburg在书中提出的想法 “对象类型”一章中的“iOS 9编程基础与Swift”:

根据他的说法,一个优雅的修复(在WWDC 2015视频中建议)是教授NSCoder,编码器类,当forKey:参数是WeekDays而不是String时该怎么做。所以在扩展中,你可以重载encodeObject:forKey:method:

extension NSCoder {
    func encodeObject(objv: AnyObject?, forKey key: WeekDays) {
        self.encodeObject(objv, forKey:key.rawValue)
    }
}

然后我会尝试迭代一个WeekDays数组并将所有需要的值粘贴为一个长字符串,如:“Sunday | Monday | ...”