iPhone - NSDictionary to NSArray with preserved order
I've got a couple dictionaries in a property list, that make up a menu system for my game, like so:
New game
Easy
Normal
Hard
Load game
Recent
Older
Options
Game
Sound
etc.. Each item in this list is a dictionary.
I use UINavigationController and UITableViews to display this menu system. When an item is chosen, a new UITableViewController is pushed in the UINavigationController, together with the items of that chosen item. For exmaple, the first UITableView contain "New Game", "Load game", and "Options" in its dictionary. If the user selects options, a new UITableViewController is created with the items "Game" and "Sound" (i.e. the dictionary of "Options").
I populate the UITableView in this way:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] init] autorelease];
}
// Set up the cell...
cell.text = [[[data keyEnumerator] allObjects] objectAtIndex:inde开发者_运维技巧xPath.row];
// Data is the dictionary..
return cell;
}
But apparently, that causes the items to not come in the same order as they are defined in the property list.
Does anyone know how to preserve the order when doing what I'm trying to do?
Thanks.
Dictionaries never preserve order. You'll need to use an Array. You can either use an array instead (I don't see any reason why you would need a dictionary from your example), or you can create an array that indexes the dictionary.
So, start with the dictionary you have now, create an array, loop through the dictionary and set the array values to the keys in the dictionary.
So if your dictionary looked like this
Game Types
easy: Easy
normal: Normal
hard: Hard
Your array would look like this: ["easy", "normal", "hard"] (none of this is objective c code). You could then use the following line.
[myDictionary objectForKey:[myArray objectAtIndex: indexPath.row]]
Dictionaries should not be counted on to preserve order. That's the point of an array.
You need an array of dictionary objects that have a title and a list of options.
NSArray *options = [NSArray arrayWithObjects:@"Easy",@"Normal",@"Hard",nil];
NSDictionary *newGame = [[[NSDictionary alloc] initWithObjectsAndKeys:@"New game", @"title", options, @"options",nil]autorelease];
Your top level table will show the title of each subpage, and each subpage will display a table of its options.
精彩评论