我在这个问题上找到了一些相关主题,但我不明白那里提出的解决方案如何适用于单例类。
当我的应用程序启动时,我打电话gamestate.shardInstance()
但applicationDidBecomeActive
每次都会立即崩溃并出现相同的错误:
2017-03-22 11:09:09.102 project-mars[46108:28079112] +[project_mars.gameState encodeWithCoder:]: unrecognized selector sent to class 0x103670e60
2017-03-22 11:09:09.107 project-mars[46108:28079112] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[project_mars.gameState encodeWithCoder:]: unrecognized selector sent to class 0x103670e60'
有人可以帮我理解这个错误到底发生了什么以及如何解决它吗?谢谢!
class gameState: NSObject, NSCoding {
var GameSettings:gameSettings //Structure that stores all the game settings
var PlayerStats:gameStatistics //Structure that stores all game stats
var GameBoard:gameBoard //Contains the information of the gameboard
private static var Instance: gameState = {
let instance = gameState.loadgameState()
//Closure for configuration
return instance!
}()
private override init(){
self.GameSettings = gameSettings()
self.PlayerStats = gameStatistics()
self.GameBoard = gameBoard()
super.init()
}
class func sharedInstance() -> gameState{
return gameState.Instance
}
required init?(coder aDecoder: NSCoder) {
self.GameSettings = (aDecoder.decodeObject(forKey: "GameSettings") as? gameSettings)!
self.PlayerStats = (aDecoder.decodeObject(forKey: "PlayerStats") as? gameStatistics)!
self.GameBoard = (aDecoder.decodeObject(forKey: "GameBoard") as? gameBoard)!
}
func encode(with aCoder: NSCoder) {
aCoder.encode(gameState.sharedInstance().GameSettings, forKey: "GameSettings")
aCoder.encode(gameState.sharedInstance().PlayerStats, forKey: "PlayerStats")
aCoder.encode(gameState.sharedInstance().GameBoard, forKey: "GameBoard")
}
class func loadgameState() ->gameState? {
let path = gameState.getFilePath()
print("PATH: \(path) \n")
if gameState.fileExistsAtPath(path: path){
if let rawData = NSData(contentsOfFile: path) {
/// do we get serialized data back from the attempted path?
/// if so, unarchive it into an AnyObject, and then convert to a GameData object
if(rawData.length != 0){
if let data = NSKeyedUnarchiver.unarchiveObject(with: rawData as Data) as? gameState {
return data
}
}
}
return gameState()
}else{
return gameState()
}
}