一尘不染

如何使用NSCoder快速编码枚举?

swift

背景

我正在尝试使用NSCoding协议对String样式的枚举进行编码,但是我遇到了转换为String和从String返回的错误。

解码和编码时出现以下错误:

字符串不可转换为舞台

额外参数ForKey:通话中

    enum Stage : String
    {
        case DisplayAll    = "Display All"
        case HideQuarter   = "Hide Quarter"
        case HideHalf      = "Hide Half"
        case HideTwoThirds = "Hide Two Thirds"
        case HideAll       = "Hide All"
    }

    class AppState : NSCoding, NSObject
    {
        var idx   = 0
        var stage = Stage.DisplayAll

        override init() {}

        required init(coder aDecoder: NSCoder) {
            self.idx   = aDecoder.decodeIntegerForKey( "idx"   )
            self.stage = aDecoder.decodeObjectForKey(  "stage" ) as String    // ERROR
        }

        func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeInteger( self.idx,             forKey:"idx"   )
            aCoder.encodeObject(  self.stage as String, forKey:"stage" )  // ERROR
        }

    // ...

    }

阅读 284

收藏
2020-07-07

共1个答案

一尘不染

您需要将枚举值与原始值进行转换。在Swift 1.2(Xcode 6.3)中,如下所示:

class AppState : NSObject, NSCoding
{
    var idx   = 0
    var stage = Stage.DisplayAll

    override init() {}

    required init(coder aDecoder: NSCoder) {
        self.idx   = aDecoder.decodeIntegerForKey( "idx" )
        self.stage = Stage(rawValue: (aDecoder.decodeObjectForKey( "stage" ) as! String)) ?? .DisplayAll
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger( self.idx, forKey:"idx" )
        aCoder.encodeObject(  self.stage.rawValue, forKey:"stage" )
    }

    // ...

}

Swift 1.1(Xcode 6.1),as代替as!

    self.stage = Stage(rawValue: (aDecoder.decodeObjectForKey( "stage" ) as String)) ?? .DisplayAll

迅速1.0(6.0的Xcode)使用toRaw()fromRaw()这样的:

    self.stage = Stage.fromRaw(aDecoder.decodeObjectForKey( "stage" ) as String) ?? .DisplayAll

    aCoder.encodeObject( self.stage.toRaw(), forKey:"stage" )
2020-07-07