UserDefaults-使用自定义ENUM和STRUCT编码自定义类-错误

时间:2018-08-30 16:17:24

标签: swift xcode swift4 nsuserdefaults nscoding

我建立了这个班来拯救球员。我的最终目标是存储一个[PlayerModel]数组,以便以后可以检索它。

我的课包括一个枚举和一个结构。我不断收到错误encodeWithCoder:]: unrecognized selector sent to instance

这是我保存它的方式。

将所有内容放入模型后,

  let decoded  = UserDefaults.standard.object(forKey: "AllPlayerData") as? Data
        if let decoded = decoded {
            var decodedPlayerModel = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [PlayerModel]

            decodedPlayerModel.append(newPlayer)

            let encodedData = NSKeyedArchiver.archivedData(withRootObject: decodedPlayerModel)
            userDefaults.set(encodedData, forKey: "AllPlayerData")

        } else {

            let encodedData = NSKeyedArchiver.archivedData(withRootObject: newPlayer)
            userDefaults.set(encodedData, forKey: "AllPlayerData")
        }


class PlayerModel: NSObject, NSCoding {

    var uniqueId: String
    var name: String

    // Enum - .forward, .mid, .defence, .goalie
    var playerType: PlayerType

    // Struct
    // Number, Image, Description
    var playerInfo: PlayerInfo

    var playerNumber: Int


    init(uniqueId: String, name: String, playerType: PlayerType, playerInfo: PlayerInfo, playerNumber: Int) {
        self.uniqueId = uniqueId
        self.name = name
        self.playerType = playerType
        self.playerInfo = playerInfo
        self.playerNumber = playerNumber
    }

    required convenience init(coder aDecoder: NSCoder) {
        let uniqueId = aDecoder.decodeObject(forKey: "uniqueId") as! String
        let name = aDecoder.decodeObject(forKey: "name") as! String
        let playerType = aDecoder.decodeObject(forKey: "playerType") as! PlayerType
        let playerInfo = aDecoder.decodeObject(forKey: "playerInfo") as! PlayerInfo
        let playerNumber = aDecoder.decodeObject(forKey: "playerNumber") as! Int


        self.init(uniqueId: uniqueId,
                  name: name,
                  playerType: playerType,
                  playerInfo: playerInfo,
                  playerNumber: playerNumber)

    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(uniqueId, forKey: "uniqueId")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(playerType, forKey: "playerType")
        aCoder.encode(playerInfo, forKey: "playerInfo")
        aCoder.encode(playerNumber, forKey: "playerNumber")

    }

}

最后,我想将[PlayerModel]作为数组获得,然后可以循环浏览并使用它做任何我想做的事情。

0 个答案:

没有答案