How to Use a Nested Array to Make Your Complex Data Persistent

Matthew Campbell, April 23rd

iStock_000006265667XSmall.jpgSometimes you are working with data that is more complicated than a simply list of items. Wouldn’t it be nice to be able to make that data persistent without needing a separate file for each object in your project?

Saving Data with Arrays

Last week, I showed you how you can use NSMutableArray to save data to the iPhone’s filesystem and then retrieve the contents the next time the app is used. It turns out that you can nest arrays to build more complicated data objects and the system is smart enough to save the data these arrays in the same way.

Example

Let us think about having three arrays: savedArray, array1 and array2. savedArray is going to act as a container for array1 and array2. We are going to put data into array1 and array2 and then add these two arrays to savedArray.

In effect, this creates a two-way table of data (like a spreadsheet) that you can visualize like this:

As you can see this is a richer data structure than a simple list. But, you can save it in the same way that you did last week:

When you need to retrieve the data you simply use the same method as we discussed last week. But, you need to keep in mind that you are working with an array of arrays. So, you will need to tweek the retrieval process a bit:

You can think of savedArray above as the column in the spreadsheet and arrayWithData as the row. Like when you are working with a spreadsheet you look up the value that want by first selecting the column using objectAtIndex on savedArray and then retrieving the value from the row by using objectAtIndex on arrayWithData.

This excites me because it is a simple way to make data persistent without using a SQLite database. You can use your imagination when it comes to how you would implement this in your own object hierarchies. The other nice thing is that you only need to manage one file (as opposed to requiring a save file for each object in your app.

So what do you think? Do you have any tips on how to achieve data persistence on the iPhone?

How to Use a Nested Array to Make Your Complex Data Persistent…

You’ve been kicked (a good thing) – Trackback from iPhoneKicks.com – iPhone SDK links, community driven…

  • Hours of videos, demos & screen casts
  • SOURCE CODE
  • Detailed HANDS-ON Exercises
  • Much Much Much More
  • UIKit
  • Objective-C
  • Core Data
  • More!
  • Learn How To Make An iPhone App right now using my proven system.

    PS: Tons of us are having a blast living off our own code, join us now. Click here to get all the details.