Advice for app development iOS. ApplicationDidEnterBackground

て烟熏妆下的殇ゞ 提交于 2019-12-02 23:17:25

问题


I´m having some fun with swift and I´m trying to make a simple game. I got a few variables that changes during the game. What´s the best practice for saving those variables if applicationDidEnterBackground and for all those other functions in appDelegate.

What I believe is to store them in core data and load them when app starts up again.

Anyone with some experience around this theme?


回答1:


If its just a few variables you want to store and manage you could use NSUserDefaults.

    // Create defaults
    let defaults = NSUserDefaults.standardUserDefaults()

    // Set an int for highScoreKey in our defaults
    defaults.setInteger(10, forKey: "highScoreKey")

    // Sync/Save the defaults we've changed
    defaults.synchronize()

    // Then to retrieve our highScoreKey default we've saved
    // We create an int to store the value that is in our default
    var highScoreInt = defaults.integerForKey("highScoreKey")

    println(highScoreInt)
    // Prints 10

I'd set and save these values as soon as I have the values I need rather than in applicationDidEnterBackground though.

NSUserDefaults Class Reference




回答2:


When I started with iOS programming, I first stored data in custom text files. Then I saved arrays to disk, used NSUserDefaults, and other tools. At the end, I decided to move to CoreData since I had to save more and more data and my application was becoming too slow.

Looking back, it would have been much better if I had used CoreData from the beginning. It is very powerful and migrating to CoreData later takes a lot of time.

If you would like to use CoreData, I recommend to start with a good tutorial or a good book. I liked the book "Learning CoreData for iOS" by Tim Roadley.

An interesting alternative may be Realm. I haven't used it yet but it may be worth a look.

However, it really depends on your application. If you do not need to save a lot of data, simpler approaches may be sufficient (NSUserDefaults, etc.).

A word of caution: Apple recommends to save data continuously and not wait until the app enters into the background state. At that time, the app may be suspended at any time and you cannot be sure that your data will be saved in time.



来源:https://stackoverflow.com/questions/30331572/advice-for-app-development-ios-applicationdidenterbackground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!