【问题标题】:iPhone - NSDictionary to NSArray with preserved orderiPhone - NSDictionary 到 NSArray 保留顺序
【发布时间】:2010-02-06 19:40:42
【问题描述】:

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

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

等等。这个列表中的每一项都是一个字典。

我使用 UINavigationController 和 UITableViews 来显示这个菜单系统。当一个项目被选中时,一个新的 UITableViewController 被推送到 UINavigationController 中,以及该项目的项目。例如,第一个 UITableView 在其字典中包含“New Game”、“Load game”和“Options”。如果用户选择选项,则会创建一个新的 UITableViewController,其中包含“游戏”和“声音”项(即“选项”的字典)。

我以这种方式填充 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;
}

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

有谁知道在做我想做的事情时如何保持顺序?

谢谢。

【问题讨论】:

    标签: iphone cocoa cocoa-touch nsarray nsdictionary


    【解决方案1】:

    字典从不保持顺序。您需要使用数组。您可以改用数组(我看不出有任何理由需要您的示例中的字典),或者您可以创建一个索引字典的数组。

    所以,从你现在拥有的字典开始,创建一个数组,遍历字典并将数组值设置为字典中的键。

    如果你的字典是这样的

    Game Types
        easy: Easy
        normal: Normal
        hard: Hard
    

    你的数组应该是这样的:["easy", "normal", "hard"](这些都不是客观的 c 代码)。然后,您可以使用以下行。

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

    【讨论】:

    • 但实际上,给每个视图控制器一个单独的 NSArray 及其相应的选项。不要使用嵌套字典
    • 谢谢。我最终做的是拥有一系列字典。每个字典都有一个标题字段和一个选项字段,其中选项是一个包含更多此类字典的新数组。
    【解决方案2】:

    不应指望字典来维持秩序。这就是数组的意义所在。

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

    NSArray *options = [NSArray arrayWithObjects:@"Easy",@"Normal",@"Hard",nil];
    
    NSDictionary *newGame = [[[NSDictionary alloc] initWithObjectsAndKeys:@"New game", @"title", options, @"options",nil]autorelease];
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2011-07-25
      • 2015-08-25
      • 2011-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多