前提・実現したいこと
CoreDataに保存するためにカスタムクラスを含むDictionaryをData型にシリアライズしたい。
発生している問題・エラーメッセージ
NSKeyedArchiver.archivedData(withRootObject: dict, requiringSecureCoding: false) //-> デグレートでSIGABRTする
該当のソースコード
PcState.swift
import Foundation class ArchivePcState : NSObject, NSCoding { public enum PcState: Int { case off=0, on=1, stanby=2, hibernate=3 } var e: PcState init(e: PcState) { self.e = e } func encode(with aCoder: NSCoder) { aCoder.encode(e.rawValue, forKey: "PcState") } required convenience init?(coder aDecoder: NSCoder) { let rawCase = aDecoder.decodeObject(forKey: "PcState") as! Int self.init(e: PcState(rawValue: rawCase)!) } }
Room.swift
class Room: NSObject,NSCoding { var PCs = Dictionary<Int, ArchivePcState.PcState>() override init() { self.PCs[1] = .on self.PCs[2] = .off self.PCs[3] = .on self.PCs[4] = .stanby } init(PCs: Dictionary<Int, ArchivePcState.PcState>) { super.init() self.PCs = PCs } func encode(with aCoder: NSCoder) { aCoder.encode(PCs, forKey: "PCs") } required init?(coder aDecoder: NSCoder) { super.init() self.PCs = (aDecoder.decodeObject(forKey: "PCs") as? [Int : ArchivePcState.PcState])! } }
main.swift
func serialize(Rooms: Room) let stateDict:[Int:ArchivePcState.PcState] = Rooms.PCs as [Int : ArchivePcState.PcState] let senddata = NSKeyedArchiver.archivedData(withRootObject: stateDict, requiringSecureCoding: false)
保存したいデータ
stateDict:[Int: PcState]をData型にしたもの
試したこと
一般的なNSCodingのためのencodeやrequired initも入れていますが、クラッシュしてしまいます.
PcStateにもcodingへの準拠が必要なのでしょうか...?
補足情報(FW/ツールのバージョンなど)
Swift 4
Xcode10.1
なぜDataで返ってきているものを、わざわざNSDataにキャストして、直後にDataにキャストしているのでしょうか?
archivedData(withRootObject:) は deprecatedなので使わない方がいいです。
>>PcStateにもcodingへの準拠が必要なのでしょうか...?
Codableですかね?なぜ試してみないのでしょうか?
手元で動かしてみると
var PCs = Dictionary<Int, PcState>()
のPcStateが未定義だったり
CellState
が未定義だったりして試せません。
すみません。すぐ修正します.(質問用にコード少し変えています)
回答1件
あなたの回答
tips
プレビュー