Scene Editor Development: Trouble Conforming to Codable
For a SpriteKit scene editor to be usable, it must be able to save scenes.
Choosing a File Format
SpriteKit scene files are binary property lists with the extension .sks
. At the very least the scene editor must be able to export scenes as binary property lists.
During development I would like to view a saved scene’s data in a text editor to make sure everything saves correctly. The Foundation framework supports saving property lists as XML or binary so I decided to save the scenes as property lists. Start by saving as XML and switch to binary later in development.
PropertyListEncoder
Looking through Apple’s documentation I saw the Foundation framework has PropertyListEncoder
and PropertyListDecoder
classes to save and load property list files. I wrote the following code to save a scene:
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
let propertyListEncoder = PropertyListEncoder()
propertyListEncoder.outputFormat = .xml
let sceneData = try propertyListEncoder.encode(scene)
return .init(regularFileWithContents: sceneData)
}
Saving to a property list requires only three lines of code. Create an instance of PropertyListEncoder
, set the output format, and call the encode
function.
If you need to save data in a property list in your app, start by using PropertyListEncoder
. But I ran into problems when I tried to use PropertyListEncoder
in the scene editor.
SpriteKit Classes Don’t Conform to Codable
To encode data with PropertyListEncoder
, the data you are encoding must conform to the Codable
protocol. SpriteKit classes don’t conform to Codable
.
I searched online to see if there was a way to make SpriteKit classes conform to Codable
. To make a struct or class conform to Codable
, the struct or class must implement the following functions:
required init(from decoder: Decoder) throws {
}
func encode(to encoder: Encoder) throws {
}
I tried creating a class extension file for the SKScene
class and learned I cannot add a required initializer in a class extension file. Since I don’t have access to the source code files for Apple’s SpriteKit framework, I can’t make SpriteKit classes conform to Codable
.
Use NSKeyedArchiver to Save Scene Data
Because SpriteKit classes don’t conform to Codable
, I can’t use PropertyListEncoder
to save scenes as property lists. I have to use NSKeyedArchiver
. I will cover using NSKeyedArchiver
in the next article.