gpt4 book ai didi

swift - 如何对这个类进行编码和解码

转载 作者:行者123 更新时间:2023-11-30 10:20:09 24 4
gpt4 key购买 nike

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

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

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

最佳答案

像这样怎么样?:

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”的 bool 数组中。
  2. map 函数用于将枚举数组转换为保存原始值的 [Int]

关于swift - 如何对这个类进行编码和解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27262574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com