使用NSUserDefaults保存对象数组

时间:2016-06-04 20:54:07

标签: swift2 xcode7 nsuserdefaults


我是swift的新手,我正在尝试构建一个包含前5名玩家名称和得分的游戏,如果我只是将玩家添加到阵列中而不是重新启动游戏它会“删除”玩家,所以我正在尝试使用NSUserDefaults(我只需要存储5个字符串和5个整数),无论如何都不起作用, 代码是:

class scoreController: UITableViewController {

    var playersArray:[Player] = [Player]()

    var nameFromGame = "" //name from game vc
    var timeFromGame = 0 //time from game vc

    let tmpPlayer = Player(playerName: "", scoreTime: 0)
    let playerDefaults = NSUserDefaults.standardUserDefaults()

    override func viewDidLoad() {
        super.viewDidLoad()

        let player1 = Player(playerName: "Bil", scoreTime: 50)
        let player2 = Player(playerName: "Bob", scoreTime: 100)


        playersArray.append(player1)
        playersArray.append(player2)

         tmpPlayer.playerName = nameFromGame
         tmpPlayer.scoreTime = timeFromGame
         playersArray.append(tmpPlayer)

         playerDefaults.setObject(playersArray[11], forKey: "players")

            print(playersArray )
        }
    }

我现在只想保存它并且它崩溃了,有人知道为什么吗?以及如何将其存储在我的应用程序中以便保存数据?

谢谢你!

3 个答案:

答案 0 :(得分:2)

您的播放器对象可能是此处的问题。你必须在你的播放器类中实现两个方法(我不是快速掌握,但它是偶像同样的错误):

- (void)encodeWithCoder:(NSCoder *)encoder;
- (id)initWithCoder:(NSCoder *)decoder;

这对你有用。 希望它有所帮助!!

PD:检查这个答案 How to store custom objects in NSUserDefaults

答案 1 :(得分:1)

您的播放器类需要符合NSCoding,并且您需要存储播放器阵列的归档数据,并在提取数据时取消归档。

类别:

class Player: NSObject, NSCoding {
    var playerName: String
    var scoreTime: Int

    init(playerName: String, scoreTime: Int) {
        self.playerName = playerName
        self.scoreTime = scoreTime
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeInteger(scoreTime, forKey: "score_time")
        aCoder.encodeObject(playerName, forKey: "player_name")
    }

    required convenience init?(coder decoder: NSCoder) {
        guard let playerName = decoder.decodeObjectForKey("player_name") as? String else {
            return nil
        }
        self.init(playerName: playerName, scoreTime: decoder.decodeIntegerForKey("score_time"))
    }
}

NSUserdefaults&存档/取消存档:

    let player1 = Player(playerName: "Bil", scoreTime: 50)
    let player2 = Player(playerName: "Bob", scoreTime: 100)

    let playersArray = [player1, player2]
    let playersData  = NSKeyedArchiver.archivedDataWithRootObject(playersArray)

    let defaults = NSUserDefaults.standardUserDefaults()
    defaults.setObject(playersData, forKey: "players")
    defaults.synchronize()

    if let playersArrayData = defaults.objectForKey("players") as? NSData {
        let unarchivedPlayers = NSKeyedUnarchiver.unarchiveObjectWithData(playersArrayData) as! [Player]
        print(unarchivedPlayers)
    }

希望这会有所帮助,如果能解决您的问题,请记得选择答案并进行投票。

答案 2 :(得分:0)

需要可以打电话

playerDefaults.synchronize()

以默认值保存数据。

EDIT
正如facumenzella所说,你的另一个问题是在默认情况下存储自定义类对象。要解决这个问题,您需要在自定义Player类中实现方法,告诉它如何转换为数据。然后,您应该在将对象存储为默认值之前序列化该对象。