Home > Enterprise >  Make a node Codable in swift
Make a node Codable in swift

Time:04-14

I'd like to use a simple FileManager to persist an object, which requires Codable to work. The issue is that the object I'm trying to persist contains an SCNNode, which would require me to somehow mane SCNNode codable.

I tried to make it Codable by using code like this:

class CodebleNode: Codable {

    var name: String?
    var Xposition: Float
    var Yposition: Float
    var Zposition: Float
    
    static func createCodableNode(from node: SCNNode) -> CodableNode {
        let codableNode = CodableNode(name: node.name, xposition: node.position.x, yposition: node.position.y, zPosition: node.position.z)
        return codableNode
    }
    
    init(name: String?, xposition: Float, yposition: Float, zPosition: Float){
        self.name = name
        Xposition = xposition
        Yposition = yposition
        Zposition = zPosition
    }
}

But it would be tedious to implement a similar wrapper to support every SCNGeometry.

Would CoreData solve this problem or is there any simple code to do that?

CodePudding user response:

SceneKit predates Swift's 4's Codable API, and was never augmented to supported it. Instead, it supports Objective-C's NSCoding API (NSSecureCoding, to be exact).

It's actually possible to leverage the SCNNode implementation of NSCodable to wrap it into a Codable archive. Essentially you just use an NSArchiver to wrap the object into a Data, and that Data can then be encoded with Codable. It's possible to neatly tuck this all away into a property wrapper, which I demonstrate here:

https://stackoverflow.com/a/71279637/3141234

  • Related