0

我在这个问题上找到了一些相关主题,但我不明白那里提出的解决方案如何适用于单例类。

当我的应用程序启动时,我打电话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()
    }
}
4

1 回答 1

0

我认为您应该能够使用本地实例,而无需在这里调用单例。您已经在单例实例中

func encode(with aCoder: NSCoder) {
    aCoder.encode(gameState.GameSettings, forKey: "GameSettings")
    aCoder.encode(gameState.PlayerStats, forKey: "PlayerStats")
    aCoder.encode(gameState.GameBoard, forKey: "GameBoard")
}

请分享gameState.loadgameState()静态方法 - 我猜那里正在发生其他事情。

于 2017-03-22T16:22:32.017 回答