Anyone have any insights to encoding/decoding double linked lists with JSON? This is just the pertinent part of the class.
If I leave off the parent var, then the application (Document Based SwiftUI) saves and loads fine - no problems (except of course the parent functionality is lost).
public class Sidebar: Codable, ObservableObject, Identifiable {
public let objectWillChange = ObservableObjectPublisher()
enum CodingKeys: CodingKey {
case id
case parent
case children
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
try container.encode(parent, forKey: .parent)
try container.encode(children, forKey: .children)
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = UUID()
parent = try container.decode(Sidebar?.self, forKey: .parent)
children = try container.decode([Sidebar]?.self, forKey: .children)
}
@Published public var id: UUID?
@Published public var parent: Sidebar?
@Published public var children: [Sidebar]?
public init() {
id = UUID()
}
With the parent var inserted and working (linked) the app crashes when saving during this call with a bad access error:
public func encode(to encoder: Encoder) throws {
var singleContainer = encoder.singleValueContainer()
try singleContainer.encode(NSKeyedArchiver.archivedData(withRootObject: attrString, requiringSecureCoding: false))
}
It appears circular referenses give JSON indigestion.
Suggestions?