Xcode 12.5 NSCoding issue with SpriteKit/GameplayKit - sprite-kit

I'm working on application using SpriteKit and I'm having trouble with NSCoding on a particular object (a GKComponent object). I'm using Swift 4.0 and iOS 11 in Build Settings. The application always crashes on the line (marked with //***) where I'm trying to decode the object. I've been using the same structure for encoding/decoding other objects and they seem to work fine. Not sure why it won't work with this particular GKComponent object.I've spent hours trying to resolve this issue but couldn't figure out why.
Any help will be appreciated.
Thanks in advance!
class ItemEntity: GKEntity {
var name: String!
var embeddedSpell: KnockbackComponent?
//Other variables
init(itemName: String) {
super.init()
name = itemName
embeddedSpell = KnockbackComponent(anItem: self)
addComponent(embeddedSpell!)
//Other initializations
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "Item.name")
aCoder.encode(embeddedSpell, forKey: "Item.embeddedSpell")
super.encode(with: aCoder)
}
required convenience init?(coder aDecoder: NSCoder) {
let itemName = aDecoder.decodeObject(forKey: "Item.name") as! String
self.init(itemName: itemName)
embeddedSpell = aDecoder.decodeObject(forKey: "Item.embeddedSpell") as? KnockbackComponent
if embeddedSpell != nil {
addComponent(self.embeddedSpell!)
}
}
//Other codes
}
Other class
class KnockbackComponent: GKComponent {
weak var item: ItemEntity!
init(anItem: ItemEntity) {
item = anItem
super.init()
}
override func encode(with aCoder: NSCoder) {
aCoder.encode(item, forKey: "KnockbackComponent.item")
super.encode(with: aCoder)
}
required convenience init?(coder aDecoder: NSCoder) {
//***This line causes crash with error msg Thread 1: EXC_BAD_INSTRUCTION***//
let item = aDecoder.decodeObject(forKey: "KnockbackComponent.item") as? ItemEntity //<--error msg Thread 1: EXC_BAD_INSTRUCTION
self.init(anItem: item!)
}
//Other codes
}

I've resolved the issue by getting my GKComponent class to conform to Codable with the codes below:
override func encode(to encoder: Encoder) {
var container = encoder.container(keyedBy: CodingKeys.self)
try? (container.encode(itemEnt, forKey: .itemEnt))
}
required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let itemEntity = try container.decode(ItemEntity.self, forKey: .itemEnt)
self.init(entity: itemEntity)
}

Related

Serialize Custom subclass of CLCircularRegion with extra an property in the class

I am using this class to create an object but when I archive and unarchive from and to UserDefaults it only gives me the value of trialUrl but not it's superclass properties.Since I don't know if CLCircularRegion supports Codable protocol I'm stuck with this approach.
class TrialRegion: CLCircularRegion{
var trailUrl:URL?
init(center: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String,trailUrl:URL) {
super.init(center: center, radius: radius, identifier: identifier)
self.trailUrl = trailUrl
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(URL.self, forKey: "trialUrl")
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
guard let url = aDecoder.decodeObject(of: NSURL.self, forKey: "trialUrl") as URL? else {return}
self.trailUrl = url
}
}

Archive and unarchive a custom class(have a property as object array),always failed

I am searching for a long time on net. But no use. Please help or try to give some ideas how to achieve this.
when unarchive app crashes and i get this message:
Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason:
'*** -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (_TtCC11ArchiveTest8dogHouse3dog)
for key (NS.objects); the class may be defined in source code or a library that is not linked'
What does it means?
Anyone helps?Thanks in advance.
Now,I recognize the Terminating because other codes,like this:
enter image description here
if I try:
enter image description here
it's well done,buy why?code write in the viewDidLoad do anything else?which method linked the class?
I have a class:
let ModelPath = "Model.plist".cacheDir()
class dogHouse: NSObject , NSCoding{
var dogs:[Dog]?
required init(coder aDecoder: NSCoder)
{
dogs = aDecoder.decodeObject(forKey: "dogs") as? [Dog]
super.init()
}
func encode(with aCoder: NSCoder) {
if dogs != nil{
aCoder.encode(dogs, forKey: "dogs")
}
}
class Dog: NSObject , NSCoding {
var name : String?
required init(coder aDecoder: NSCoder)
{
name = aDecoder.decodeObject(forKey: "name") as! String?
super.init()
}
func encode(with aCoder: NSCoder) {
if name != nil{
aCoder.encode(name, forKey: "name")
}
}
//ArchiveModels
func saveModel() -> Bool{
return NSKeyedArchiver.archiveRootObject(self, toFile: ICModelPath)
}
//UnArchiveModels
class func loadArchiver() -> [Dog]?{
let obj = NSKeyedUnarchiver.unarchiveObject(withFile: ICModelPath)
if obj != nil {
print(obj.debugDescription)
let model = obj as? dogHouse
return model?.dogs
}
return nil
}
}
Maybe you missed a parameter in the init function?
required init(coder aDecoder: NSCoder)
{
dogs = aDecoder.decodeObject(forKey: "dogs") as? [Dog]
super.init(aDecoder) //HERE
}

How to make singleton class from class, which inherits from nsobject and nscoding?

I am trying to make the game settings which loads, saves itself, and makes it singleton class. All my efforts lead to failure, XCode asks me "Cannot invoke initializer for type "Settings" with no arguments". How can I fix this?
This is the code:
class Settings: NSObject, NSCoding {
static let sharedInstance = Settings()
var currentLevel: Int
var positionOfPlayer: [Int]?
var sounds: Bool
var shape: String
var completedLevels: [Int: Bool]
init?(currentLevel: Int, positionOfPlayer: [Int]?, sounds: Bool, shape: String, completedLevels: [Int: Bool]) {
self.currentLevel = currentLevel
self.sounds = sounds
self.shape = shape
self.completedLevels = completedLevels
if let position = positionOfPlayer as [Int]? {
self.positionOfPlayer = position
}
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let currentLevel = aDecoder.decodeObjectForKey(SettingNames.nameOfCurrentLevel) as? Int
let completedLevels = aDecoder.decodeObjectForKey(SettingNames.nameOfCompletedLevels) as? [Int: Bool]
let positionOfPlayer = aDecoder.decodeObjectForKey(SettingNames.positionOfPlayerOnCurrentLevel) as? [Int]
let sounds = aDecoder.decodeObjectForKey(SettingNames.nameOfSounds) as? Bool
let shape = aDecoder.decodeObjectForKey(SettingNames.nameOfShapes) as? String
self.init(currentLevel: currentLevel!, positionOfPlayer: positionOfPlayer, sounds: sounds!, shape: shape!, completedLevels: completedLevels!)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(currentLevel, forKey: SettingNames.nameOfCurrentLevel)
aCoder.encodeObject(completedLevels, forKey: SettingNames.nameOfCompletedLevels)
if let position = positionOfPlayer as [Int]? {
// If game canceled or ended during playing, it saves the current player position.
// Next time, when player open the game, it will continue
aCoder.encodeObject(position, forKey: SettingNames.positionOfPlayerOnCurrentLevel)
}
aCoder.encodeBool(sounds, forKey: SettingNames.nameOfSounds)
aCoder.encodeObject(shape, forKey: SettingNames.nameOfShapes)
}
}
You're trying to access a constructor which accepts no parameters which was not implemented for the current class. Try overriding the init method, that should remove the error.
override init(){
// some code
}
Here's a full example I've tried:
import Foundation
class Settings : NSObject, NSCoding {
static let sharedInstance = Settings()
var a: String?
var b: String?
convenience init(a: String, b: String){
self.init()
self.a = a
self.b = b
}
override init(){
}
required init?(coder aDecoder: NSCoder) {
}
func encodeWithCoder(aCoder: NSCoder) {
}
}
Just a point of view: a Singleton that requires you to pass parameters in order to configure it does no longer behave like a singleton.

Encoding/Decoding an array of objects which implements a protocol in Swift 2

I have got a class that inherits from NSObject and I want it to be NSCoding compliant. But I ran into trouble while encoding an array of objects which should implement a protocol.
protocol MyProtocol {
var myDescription: String { get }
}
class DummyClass: NSObject, NSCopying, MyProtocol {
var myDescription: String {
return "Some description"
}
func encodeWithCoder(aCoder: NSCoder) {
// does not need to do anything since myDescription is a computed property
}
override init() { super.init() }
required init?(coder aDecoder: NSCoder) { super.init() }
}
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection = aDecoder.decodeObjectForKey("collection") as! [MyProtocol]
self.init(myCollection: collection)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(myCollection, forKey: "collection")
}
}
For aCoder.encodeObject(myCollection, forKey: "collection") I get the error:
Cannot convert value of type '[MyProtocol]' to expected argument type 'AnyObject?'
OK, a protocol obviously is not an instance of a class and so it isn't AnyObject? but I've no idea how to fix that. Probably there is a trick that I'm not aware? Or do you do archiving/serialization differently in Swift as in Objective-C?
There's probably a problem with let collection = aDecoder.decodeObjectForKey("collection") as! [MyProtocol], too but the compiler doesn't complain yet…
I've just found the solution myself: The key is to map myCollection into [AnyObject] and vice-versa, like so:
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection1 = aDecoder.decodeObjectForKey("collection") as! [AnyObject]
let collection2: [MyProtocol] = collection1.map { $0 as! MyProtocol }
self.init(myCollection: collection2)
}
func encodeWithCoder(aCoder: NSCoder) {
let aCollection: [AnyObject] = myCollection.map { $0 as! AnyObject }
aCoder.encodeObject(aCollection, forKey: "collection")
}
}
I know your title specifies Swift 2, but just for reference, for a similar problem I was working on, I found that in Swift 3, you don't need to convert anymore to AnyObject.
The following works for me in Swift 3 (using your example):
class MyClass: NSObject, NSCoding {
let myCollection: [MyProtocol]
init(myCollection: [MyProtocol]) {
self.myCollection = myCollection
super.init()
}
required convenience init?(coder aDecoder: NSCoder) {
let collection = aDecoder.decodeObject(forKey: "collection") as! [MyProtocol]
self.init(myCollection: collection)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encode(aCollection, forKey: "collection")
}
}

Saving Array with NSCoding

I have a small app that has a few saving functionalities. I have a data model class called: Closet:
class Department: NSObject, NSCoding {
var deptName = ""
var managerName = ""
var Task: [Assignment]? // <----- assignment class is in example 2
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(deptName, forKey: "deptName")
aCoder.encodeObject(managerName, forKey: "mngName")
// aCoder.encodeObject(Task, forKey: "taskArray")
}
required init(coder aDecoder: NSCoder) {
super.init()
course = aDecoder.decodeObjectForKey("deptName") as! String
instructor = aDecoder.decodeObjectForKey("mngName") as! String
// Task = aDecoder.decodeObjectForKey("tasKArray") as? [Assignment]
}
override init() {
super.init()
}
}
So this is the main controller data model which in the first View Controller, a user is able to tap the "+" button to add a department name and manager name. The problem is not with saving this as i save it successfully using NSKeyedArchive and loads it back when the app starts.
The Problem:
I want to add an array of assignments on this data model Department called Assignment which would have a title and a notes variable. This is the Data model for Assignment:
Assignment.swift
class Assignment: NSObject, NSCoding {
var title = ""
var notes = ""
func encodeWithCoder(aCoder: NSCoder) {
// Methods
aCoder.encodeObject(title, forKey: "Title")
aCoder.encodeObject(notes, forKey: "notepad")
}
required init(coder aDecoder: NSCoder) {
// Methods
title = aDecoder.decodeObjectForKey("Title") as! String
notes = aDecoder.decodeObjectForKey("notepad") as! String
super.init()
}
override init() {
super.init()
}
}
So what i am essentially trying to achieve is an app where a user enters different departments with different manager names which work now in my app, but within a department, the user can click the "+" button to add an assignment title and notes section that can be editable when clicked which i can handle afterwards. These assignments are different from department to department.
My big problem is achieving this functionality. I can't seem to get this working.
I want this array assigment property to be part of the Department Class so each cell can have their own sort of To-Do list. any help would definitely help me out a lot. Thanks :)
You are using NSCoder correctly, but there are two errors in capitalization. The first error affects the functionality of the application, and the second error is a stylistic mistake. You encoded Task with the key "taskArray", but you tried to decode it with the key "tasKArray". If you fix the capital K in the latter, then your code will work.
The second capitalization error is a stylistic mistake: Task, like all properties in Swift, should be written in lowerCamelCase (llamaCase).
Be sure to pay close attention to indentation. In programming, there are special indentation rules we follow that help make code clear. Here is the corrected code with proper capitalization and indentation:
class Department: NSObject, NSCoding {
var deptName = ""
var managerName = ""
var task: [Assignment]?
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(deptName, forKey: "deptName")
aCoder.encodeObject(managerName, forKey: "mngName")
aCoder.encodeObject(task, forKey: "taskArray")
}
required init(coder aDecoder: NSCoder) {
super.init()
course = aDecoder.decodeObjectForKey("deptName") as! String
instructor = aDecoder.decodeObjectForKey("mngName") as! String
task = aDecoder.decodeObjectForKey("taskArray") as? [Assignment]
}
override init() {
super.init()
}
}
class Assignment: NSObject, NSCoding {
var title = ""
var notes = ""
func encodeWithCoder(aCoder: NSCoder) {
// Methods
aCoder.encodeObject(title, forKey: "Title")
aCoder.encodeObject(notes, forKey: "notepad")
}
required init(coder aDecoder: NSCoder) {
// Methods
title = aDecoder.decodeObjectForKey("Title") as! String
notes = aDecoder.decodeObjectForKey("notepad") as! String
super.init()
}
override init() {
super.init()
}
}
Updated for Swift 5 / Xcode Version 12.4 (12D4e)
Thanks for the example above Tone416 -- I've reworked it for Swift 5 as the protocols and methods have changed. I've also included a simple test to prove it out so you should be able to just cut and paste this into a playground a run it.
import Foundation
class Department: NSObject, NSCoding {
var deptName = ""
var managerName = ""
var task: [Assignment]?
func encode(with coder: NSCoder) {
coder.encode(deptName, forKey: "deptName")
coder.encode(managerName, forKey: "mngName")
coder.encode(task, forKey: "taskArray")
}
required init(coder aDecoder: NSCoder) {
super.init()
deptName = aDecoder.decodeObject(forKey: "deptName") as! String
managerName = aDecoder.decodeObject(forKey: "mngName") as! String
task = aDecoder.decodeObject(forKey: "taskArray") as? [Assignment]
}
override init() {
super.init()
}
convenience init(deptName: String, managerName: String, task: [Assignment]?) {
self.init()
self.deptName = deptName
self.managerName = managerName
self.task = task
}
}
class Assignment: NSObject, NSCoding {
var title = ""
var notes = ""
func encode(with coder: NSCoder) {
// Methods
coder.encode(title, forKey: "Title")
coder.encode(notes, forKey: "notepad")
}
required init(coder aDecoder: NSCoder) {
// Methods
title = aDecoder.decodeObject(forKey: "Title") as! String
notes = aDecoder.decodeObject(forKey: "notepad") as! String
super.init()
}
override init() {
super.init()
}
convenience init(title: String, notes: String) {
self.init()
self.title = title
self.notes = notes
}
}
// Create some data for testing
let assignment1 = Assignment(title: "title 1", notes: "notes 1")
let assignment2 = Assignment(title: "title 2", notes: "notes 2")
let myDepartment = Department(deptName: "My Dept", managerName: "My Manager", task: [assignment1, assignment2])
// Try archive and unarchive
do {
// Archive
let data = try NSKeyedArchiver.archivedData(withRootObject: myDepartment, requiringSecureCoding: false)
print ("Bytes in archive: \(data.count)")
// Unarchive
let obj = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! Department
// Print the contents of the unarchived object
print("Department: \(obj.deptName) Manager: \(obj.managerName)")
if let task = obj.task {
for i in 0...task.count-1 {
print("Task: \(task[i].title) \(task[i].notes)")
}
}
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
Enjoy