Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If NSDictionary is good for paired values, what is good for triple values?

NSDictionary is good for key-value pairs, by what data structure is best for when you have three values? Is is best to create a class for those 3 values, and then let each object in an array contain instances of that class?

To be specific: The data structure, let's call it Person, I envisage has three values: (NSString)name, (int)age, (BOOL)isAlive

These would be held in array(?). It's important to be able to both use the name as a key, and also refer to the whole block with a number, starting at zero.

like image 873
cannyboy Avatar asked Jun 19 '09 11:06

cannyboy


2 Answers

If you have one key and two values, you would probably create a class for the two values and still use a dictionary.

If you have two keys and one value, you would probably use a nested dictionary - that is, a dictionary where the key is the first key and the value is another dictionary. The key for the nested dictionary would be the second key, and the value would be your actual value.

ETA:

Now that you've clarified your question - if you need to access your collection both by key or by integer index, you can still use a dictionary.

To get an item by key, you would do this:

[myDict objectForKey:@"joe"];

To get an item by index, you could use the allKeys array:

[myDict objectForKey:[[myDict allKeys] objectAtIndex:1]];

If the only purpose for getting the people by index is looping over the entire collection, you'd be better off looking into using the keyEnumerator method to enumerate the keys in a loop and use those keys to look up the values.

like image 124
Eric Petroelje Avatar answered Sep 19 '22 20:09

Eric Petroelje


You can use core data to represent more complex data relationships, using a relational database model.

Check out apple's developer site for examples and documentation.

like image 1
Alex Brown Avatar answered Sep 20 '22 20:09

Alex Brown