当我尝试使用Swift 4中的Codable升级和减少代码时,我正在努力理解类/引用类型行为及其与更改的关系。
我有两个类 - 一个SuperClass,其中所有数据都是持久的,我保存到UserDefaults(地名和带坐标的字符串),以及一个包含额外的临时信息的SubClass,我不会这样做。 ; t需要(SuperClass坐标的天气数据)。
在Swift 3中我曾经保存过这样的数据:
func saveUserDefaults() {
var superClassArray = [SuperClass]()
// subClassArray is of type [SubClass] and contains more data per element.
superClassArray = subClassArray
let superClassData = NSKeyedArchiver.archivedData(withRootObject: superClassArray)
UserDefaults.standard.set(superClassData, forKey: " superClassData")
}
SuperClass符合NSObject& NSCoding 它还包括所需的init解码器&编码功能。 这一切都很好。
尝试切换到Swift 4&可编码我修改了SuperClass以符合Codable。 SuperClass现在只有一个基本的初始化器,而且没有来自Swift 3的编码器/解码器。这种新方法没有发生KeyedArchiving(下面)。 SubClass保持不变。不幸的是,我在尝试的线路上崩溃了? encoder.encode [给出一个线程1:EXC_BAD_ACCESS(代码= 1,地址= 0x10)]。我的假设是编码器与相同的引用类型混淆,其中一个是SuperClass和一个SubClass(subClassArray [0] === superClassArray [0]为真)。 我认为这可能有用:
func saveUserDefaults() {
var superClassArray = [SuperClass]()
superClassArray = subClassArray
// assumption was that the subclass would only contain parts of the superclass & wouldn't produce an error when being encoded
let encoder = JSONEncoder()
if let encoded = try? encoder.encode(superClassArray){
UserDefaults.standard.set(encoded, forKey: " superClassArray ")
} else {
print("Save didn't work!")
}
}
然后,不是创建一个空的superClassArray,而是使用: superClassArray = subClassArray,如上所示,我将其替换为单行:
let superClassArray: [SuperClass] = subClassArray.map{SuperClass(name: $0.name, coordinates: $0.coordinates)}
这很有效。同样,假设是因为我传入了类引用类型中的值&没有做过superClassArray = subClassArray。另外,正如预期的那样,subClassArray [0] === superClassArray [0]为假
那为什么"旧东西"在Swift 3中工作,即使我在let superClassData = NSKeyedArchiver.archivedData(withRootObject:superClassArray)之前使用了行superClassArray = subClassArray ?通过在Swift 4中创建与旧Swift 3编码器/解码器一起发生的数组,我基本上实现了相同的结果吗?是循环/重新创建
谢谢!
答案 0 :(得分:2)
多态持久性似乎被设计破坏。
上的回复与现有的NSCoding API(NSKeyedArchiver)不同,新的Swift 4 Codable实现不会将编码类型的类型信息写入生成的归档中,以实现灵活性和安全性。因此,在解码时,API只能使用您提供的具体类型来解码值(在您的情况下,超类类型)。
这是设计的 - 如果您需要执行此操作所需的动态,我们建议您采用NSSecureCoding并使用NSKeyedArchiver / NSKeyedUnarchiver
我没有打动,从所有发光文章中想到,Codable是我祈祷的答案。作为对象工厂的一组并行的Codable结构是我考虑保留类型信息的一种解决方法。
更新我使用管理重新创建多态类的单个结构编写了一个示例。可在GitHub上找到。
我不能够通过子类化轻松地使用它。但是,符合基本协议的类可以应用Codable
进行默认编码。回购包含密钥和非密钥方法。更简单的是unkeyed, copied below
// Demo of a polymorphic hierarchy of different classes implementing a protocol
// and still being Codable
// This variant uses unkeyed containers so less data is pushed into the encoded form.
import Foundation
protocol BaseBeast {
func move() -> String
func type() -> Int
var name: String { get }
}
class DumbBeast : BaseBeast, Codable {
static let polyType = 0
func type() -> Int { return DumbBeast.polyType }
var name:String
init(name:String) { self.name = name }
func move() -> String { return "\(name) Sits there looking stupid" }
}
class Flyer : BaseBeast, Codable {
static let polyType = 1
func type() -> Int { return Flyer.polyType }
var name:String
let maxAltitude:Int
init(name:String, maxAltitude:Int) {
self.maxAltitude = maxAltitude
self.name = name
}
func move() -> String { return "\(name) Flies up to \(maxAltitude)"}
}
class Walker : BaseBeast, Codable {
static let polyType = 2
func type() -> Int { return Walker.polyType }
var name:String
let numLegs: Int
let hasTail: Bool
init(name:String, legs:Int=4, hasTail:Bool=true) {
self.numLegs = legs
self.hasTail = hasTail
self.name = name
}
func move() -> String {
if numLegs == 0 {
return "\(name) Wriggles on its belly"
}
let maybeWaggle = hasTail ? "wagging its tail" : ""
return "\(name) Runs on \(numLegs) legs \(maybeWaggle)"
}
}
// Uses an explicit index we decode first, to select factory function used to decode polymorphic type
// This is in contrast to the current "traditional" method where decoding is attempted and fails for each type
// This pattern of "leading type code" can be used in more general encoding situations, not just with Codable
//: **WARNING** there is one vulnerable practice here - we rely on the BaseBeast types having a typeCode which
//: is a valid index into the arrays `encoders` and `factories`
struct CodableRef : Codable {
let refTo:BaseBeast //In C++ would use an operator to transparently cast CodableRef to BaseBeast
typealias EncContainer = UnkeyedEncodingContainer
typealias DecContainer = UnkeyedDecodingContainer
typealias BeastEnc = (inout EncContainer, BaseBeast) throws -> ()
typealias BeastDec = (inout DecContainer) throws -> BaseBeast
static var encoders:[BeastEnc] = [
{(e, b) in try e.encode(b as! DumbBeast)},
{(e, b) in try e.encode(b as! Flyer)},
{(e, b) in try e.encode(b as! Walker)}
]
static var factories:[BeastDec] = [
{(d) in try d.decode(DumbBeast.self)},
{(d) in try d.decode(Flyer.self)},
{(d) in try d.decode(Walker.self)}
]
init(refTo:BaseBeast) {
self.refTo = refTo
}
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let typeCode = try container.decode(Int.self)
self.refTo = try CodableRef.factories[typeCode](&container)
}
func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
let typeCode = self.refTo.type()
try container.encode(typeCode)
try CodableRef.encoders[typeCode](&container, refTo)
}
}
struct Zoo : Codable {
var creatures = [CodableRef]()
init(creatures:[BaseBeast]) {
self.creatures = creatures.map {CodableRef(refTo:$0)}
}
func dump() {
creatures.forEach { print($0.refTo.move()) }
}
}
//: ---- Demo of encoding and decoding working ----
let startZoo = Zoo(creatures: [
DumbBeast(name:"Rock"),
Flyer(name:"Kookaburra", maxAltitude:5000),
Walker(name:"Snake", legs:0),
Walker(name:"Doggie", legs:4),
Walker(name:"Geek", legs:2, hasTail:false)
])
startZoo.dump()
print("---------\ntesting JSON\n")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let encData = try encoder.encode(startZoo)
print(String(data:encData, encoding:.utf8)!)
let decodedZoo = try JSONDecoder().decode(Zoo.self, from: encData)
print ("\n------------\nAfter decoding")
decodedZoo.dump()