如何编码和解码这个类

时间:2014-12-03 02:19:07

标签: swift nscoding

在这里,我想归档和取消归档我的自定义类,这里是代码段。

enum Type: Int {
case Fruit
case Meat
case Drink
}

class ShoppingList {

    var typeOne: [Type]!

    var typeTwo: [Type]!

    var typeThree: [Type]!

    init(coder aDecoder: NSCoder) {

        // how to decode enum-based array
    }

    func encodeWithCoder(aCoder: NSCoder) {

        // how to encode enum-based array
    }
}

我想知道如何实现这两种方法。

1 个答案:

答案 0 :(得分:1)

这样的事情怎么样?:

class ShoppingList: NSObject, NSCoding {

    var typeOne: [Type]!

    var typeTwo: [Type]!

    var typeThree: [Type]!

    override init() {
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        let nils = aDecoder.decodeObjectForKey("nils") as [Bool]
        if nils[0] {
            typeOne = nil
        } else {
            let typeOneInt = aDecoder.decodeObjectForKey("typeOneInt") as [Int]
            self.typeOne = typeOneInt.map{Type(rawValue: $0) ?? .Fruit}
        }
        if nils[1] {
            typeTwo = nil
        } else {
            let typeTwoInt = aDecoder.decodeObjectForKey("typeTwoInt") as [Int]
            self.typeTwo = typeTwoInt.map{Type(rawValue: $0) ?? .Fruit}
        }
        if nils[2] {
            typeThree = nil
        } else {
            let typeThreeInt = aDecoder.decodeObjectForKey("typeThreeInt") as [Int]
            self.typeThree = typeThreeInt.map{Type(rawValue: $0) ?? .Fruit}
        }
    }

    func encodeWithCoder(aCoder: NSCoder) {
        let nils:[Bool] = [typeOne == nil, typeTwo == nil, typeThree == nil]
        aCoder.encodeObject(nils, forKey:"nils")

        if typeOne != nil {
            let typeOneInt:[Int] = typeOne.map{$0.rawValue}
            aCoder.encodeObject(typeOneInt, forKey:"typeOneInt")
        }
        if typeTwo != nil {
            let typeTwoInt:[Int] = typeTwo.map{$0.rawValue}
            aCoder.encodeObject(typeTwoInt, forKey:"typeTwoInt")
        }
        if typeThree != nil {
            let typeThreeInt:[Int] = typeThree.map{$0.rawValue}
            aCoder.encodeObject(typeThreeInt, forKey:"typeThreeInt")
        }
    }
}

评论:

  1. 我想知道列表可能是零的事实。它存储在名为" nils"。
  2. 的布尔数组中
  3. map函数用于将枚举数组转换为包含原始值的[Int]