试图在SpriteKit编辑器中静默地使用GKComponent子类会在保存时导致Xcode崩溃



我正在尝试使用Xcode中的场景编辑器来处理GameplayKit和SpriteKit。我是SpriteKit的新手,以前也没有使用过NSSecureEncoding。说实话,在swift还是个新手。

我有一个基本的GKComponent子类,具有一个整数一字符串属性,实现方式如下。

import Foundation
import GameplayKit
@objc
class BasicComponent: GKComponent {
@GKInspectable var number: Int = 0
@GKInspectable var text: String = " "
struct CoderKeys {
static let stringKey = "StringKey"
static let integerKey = "IntegerKey"
}
override static var supportsSecureCoding: Bool  {
return true
}
required convenience init?(coder aDecoder: NSCoder) {
self.init(coder: aDecoder)
if let num = aDecoder.decodeObject(of: NSNumber.self, forKey: CoderKeys.integerKey) { self.number = num.intValue }
if let tex = aDecoder.decodeObject(of: NSString.self, forKey: CoderKeys.stringKey) { self.text = tex as String }
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(self.number as NSNumber, forKey: CoderKeys.integerKey)
aCoder.encode(self.text as NSString, forKey: CoderKeys.stringKey)
}

}

每次将此组件添加到节点时,Xcode都会在场景保存(自动保存或故意保存(时静默崩溃。Xcode崩溃日志文件中的回溯显示NSInvalidArgumentException:

UNCAUGHT EXCEPTION (NSInvalidArgumentException): *** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[3]
UserInfo: (null)
Hints:
Backtrace:
0   __exceptionPreprocess (in CoreFoundation)
1   DVTFailureHintExceptionPreprocessor (in DVTFoundation)
2   objc_exception_throw (in libobjc.A.dylib)
3   -[CFPrefsConfigurationFileSource initWithConfigurationPropertyList:containingPreferences:] (in CoreFoundation)
4   -[__NSPlaceholderArray initWithObjects:count:] (in CoreFoundation)
5   +[NSArray arrayWithObjects:count:] (in CoreFoundation)
6   -[GTFSceneCustomComponentProperty initWithCoder:] (in GameToolsFoundation)
7   _decodeObjectBinary (in Foundation)
8   -[NSKeyedUnarchiver _decodeArrayOfObjectsForKey:] (in Foundation)
9   -[NSDictionary(NSDictionary) initWithCoder:] (in Foundation)
10   _decodeObjectBinary (in Foundation)
11   _decodeObject (in Foundation)
12   -[NSKeyedUnarchiver decodeObjectForKey:] (in Foundation)
13   -[NSKeyedUnarchiver decodeObjectOfClasses:forKey:] (in Foundation)
14   -[GTFSceneCustomComponent initWithCoder:] (in GameToolsFoundation)
15   _decodeObjectBinary (in Foundation)
16   -[NSKeyedUnarchiver _decodeArrayOfObjectsForKey:] (in Foundation)
17   -[NSArray(NSArray) initWithCoder:] (in Foundation)
18   _decodeObjectBinary (in Foundation)
19   _decodeObject (in Foundation)
20   -[NSKeyedUnarchiver decodeObjectForKey:] (in Foundation)

在读取回溯方面也是新的,但在我看来,init?(coder:(失败并返回一个null对象,这导致了错误。

此外,如果我删除String属性,这将完美地工作。我不知道初始化的原因是什么?失败。。。

不管怎样,我可能会偏离底线,但我很确定我错过了一些简单的东西,看起来会很愚蠢,但我就是想不通。

谢谢你的帮助。

使用NSString而不是String

最新更新