Data Persistence

All apps have some data that needs to be saved. Data can be saved temporarily (in memory) - which means it will be available only during current app session. If you will close it and open sometime later, data will be gone.

Sometimes this type of behavior is not acceptable, and we need to persist the data. To do it, we will need to use databases.

We will learn three ways to store the data in this book:

NSUserDefaults

We will start with the simplest way to save a file. With sugarcube saving to NSUserdefaults can be done with just one line of code:

        NSUserDefaults["name"] = "John"

        # or something more difficult:
        NSUserDefaults["user_profile"] = {
          name: {
            first: "John",
            last: "Smith"
          },
          languages: ["Ruby", "Python", "Objective-C"]
        }

        # then to access it:
        NSUserDefaults["user_profile"]

        # or:
        NSUserDefaults["user_profile"]["name"]["first"]
        NSUserDefaults["user_profile"]["languages"][0]
      

NSUserDefaults's purpose is to persist only small pieces of data: user details, app preferences, etc. You can read or write to it anywhere inside of the app: in screens, models, table cells.

Data saved in NSUserDefaults will always be available. The user can close the app, reboot his device, and data still will be there. However, if the user removes the app, all data will be gone as well.

You can save almost anything to NSUserDefaults:

However you need to remember that when you save nil value, sugarcube will convert it into false.

Again, you should never use NSUserDefaults for large amounts of data. NSUserDefaults is made as a fast and easy way to save and retrieve something small. However, it is an extremely slow tool to save and read something bigger that application settings.

Book Index | Next