Issue with NSDataStorage in simple reflex test game app

ⅰ亾dé卋堺 提交于 2019-12-06 08:04:50

You've almost got the idea with NSUserDefaults—just read and write as needed. I always like to abstract that away into methods (or even separate objects) that have an intuitive interface like save and load.

If your data gets more complex, you may want to look into writing data to a file on the device with NSKeyedArchiver and NSCoding in order to serialize and deserialize easily.

See this NSHipster Article for more info on that.

class ViewController: UIViewController {
    var arr = [Int]()

    let kDefaultsKey = "com.mycompany.myapp.numbers"

    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadDefaults()
    }

    func randomNumner() -> Int {
        return Int(arc4random() % 100)
    }

    @IBAction func buttonTapped(sender: AnyObject) {
        arr.append( randomNumber() )
        self.saveDfeaults()
    }

    func loadDefaults() {
        if let savedArray = NSUserDefaults.standardUserDefaults().objectForKey( kDefaultsKey ) as? [Int] {
            self.arr = savedArray
        }
    }

    func saveDfeaults() {
        NSUserDefaults.standardUserDefaults().setObject( self.arr, forKey: kDefaultsKey )
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!