user116170 user116170 - 1 year ago 73
iOS Question

How to represent tabular data in Objective-C

What is the best way to represent this data structure? I'm using Objective-C for iPhone development but just generally is fine.

Location1 Location2 Location3
Location1 0 8 23
Location2 8 0 16
Location3 23 16 0

I could do nested arrays...

table = ['Location1' => ['Location 1' => '0',
'Location 2' => '8',
'Location 3' => '23'],
'Location2' => ['Location 1' => '8',
'Location 2' => '0',
'Location 3' => '16'],
'Location3' => ['Location 1' => '23',
'Location 2' => '16',
'Location 3' => '0']]

... but I'm not sure this is the most efficient way as there's a lot of data replication. Maybe some sort of object-oriented method?

Additionally, are there any special iPhone Objective-C data structures that would lend themselves to this kind of data?

Answer Source

You could use an array of arrays, that is NSArray objects that contain other NSArray objects that contain the data. The downside to this approach is that it is up to your program to enforce limits on the size of the array so that each row and column has a consistent size. If your data is static and plist-able (contains only strings, numbers, dates, data, arrays or dictionaries), consider storing it in a plist file, and loading it in one go using [NSArray arrayWithContentsOfFile:].

If you wish to access the data using keys such as Location1, then you'll need to use NSDictionary objects instead of NSArray objects; however doing this you lose the ability to access the data sequentially or by numerical index (it must always be accessed by key).

Also, if your data is mutable (that is, you want to be able to alter the data), you'll need to use NSMutableArray or NSMutableDictionary.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download