0

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?

Michael
  • 185
  • 1
  • 11
  • 1
    SCNNode conforms to [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding), you might want to check out if that is of use for you. – Joakim Danielson Apr 13 '22 at 17:11
  • I wanted to be able to save data with a FileManager and I couldn't find any information how to do that. I'll edit my text. – Michael Apr 13 '22 at 18:35
  • Because I thought that CoreData might not require Codable, but I read through my the internet, I saw that Core Data requires that, too. And the FileManager does the same thing. – Michael Apr 13 '22 at 19:03

1 Answers1

2

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

Alexander
  • 59,041
  • 12
  • 98
  • 151