iPhone - NSDray到NSArray保留订单

时间:2010-02-06 19:40:42

标签: iphone cocoa cocoa-touch nsarray nsdictionary

我在一个属性列表中有一些词典,它构成了我游戏的菜单系统,如下所示:

New game
    Easy
    Normal
    Hard
Load game
    Recent
    Older
Options
    Game
    Sound

等。此列表中的每个项目都是字典。

我使用UINavigationController和UITableViews来显示这个菜单系统。选择项目后,UINavigationController中将推送一个新的UITableViewController以及所选项目的项目。例如,第一个UITableView在其词典中包含“新游戏”,“加载游戏”和“选项”。如果用户选择了选项,则会创建一个新的UITableViewController,其中包含“Game”和“Sound”项(即“Options”字典)。

我以这种方式填充UITableView:

- (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:indexPath.row];

    // Data is the dictionary..

    return cell;
}

但显然,这导致项目的顺序与属性列表中定义的顺序不同。

有人知道在做我想做的事情时如何保留订单吗?

感谢。

2 个答案:

答案 0 :(得分:5)

词典永远不会保留秩序。你需要使用一个数组。您可以使用数组(我没有看到您需要示例中的字典的任何原因),或者您可以创建一个索引字典的数组。

因此,从现在的字典开始,创建一个数组,遍历字典并将数组值设置为字典中的键。

所以如果你的字典看起来像这样

Game Types
    easy: Easy
    normal: Normal
    hard: Hard

你的数组看起来像这样:[“easy”,“normal”,“hard”](这些都不是客观的c代码)。然后,您可以使用以下行。

[myDictionary objectForKey:[myArray objectAtIndex: indexPath.row]]

答案 1 :(得分:3)

不应指望词典保留秩序。这就是阵列的重点。

您需要一个包含标题和选项列表的字典对象数组。

NSArray *options = [NSArray arrayWithObjects:@"Easy",@"Normal",@"Hard",nil];

NSDictionary *newGame = [[[NSDictionary alloc] initWithObjectsAndKeys:@"New game", @"title", options, @"options",nil]autorelease];

您的顶级表格将显示每个子页面的标题,每个子页面将显示其选项的表格。