2014-12-03 37 views
0

在這裏,我想歸檔並取消存檔我的自定義類,這裏是代碼片段。如何對此類進行編碼和解碼

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

我在想如何實現這兩種方法。

+0

您可以將其轉換爲'NSDictionary',並將其存儲在json/plist文件中。或者如果你尋找更緊湊的東西(比如字節而不是xml/json),可以使用'NSArchiver'。 – 2014-12-03 02:49:01

+1

這個想法是編碼/解碼您的實例變量,以便您可以從編碼器重建它們。不管你喜歡做到這一點。思考一種代表一系列類型(順便選擇名字的可怕選擇)作爲可歸檔對象的方式完全取決於你。請記住,必須出來的東西,你需要一個完全可逆的表示。 – matt 2014-12-03 03:07:42

+0

謝謝,matt.I已根據您的建議找出瞭解決方案。 – tounaobun 2014-12-03 03:18:58

回答

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. 映射函數用於將枚舉數組轉換爲保存原始值的[Int]
+0

這現在已經過測試,它的工作原理。 – vacawama 2014-12-03 04:35:43

+0

Thanks.vacawama。 – tounaobun 2014-12-03 05:29:24

相關問題