ios - 使用自定义顺序对 NSArray 进行排序

标签 ios cocoa-touch nsarray nsdictionary

我有一个 NSMutableDictionary 对象,其中包含一个 iPhone 应用程序的菜单项列表。菜单项的所需顺序不是按字母顺序排列的,因此对键进行排序的标准方式并不是真正的选择。我的字典如下,并按所需顺序初始化(我知道字典没有排序——我需要按此顺序对键数组进行排序):

    menuDict = [[NSMutableDictionary alloc] init];
    [menuDict setObject:@"Main Menu" forKey:@"EntryViewController"];
    [menuDict setObject:@"States Lookup" forKey:@"AllStatesViewController"];
    [menuDict setObject:@"Favorites" forKey:@"FavoritesViewController"];
    [menuDict setObject:@"Help" forKey:@"HelpViewController"];
    [menuDict setObject:@"About" forKey:@"AboutViewController"];

如何获取键列表并按照与该字典相同的顺序对它们进行排序?谢谢!

最佳答案

你不能,NSDictionary 不保存添加项目的顺序。为此,您应该使用 NSArray

以下是您如何使用它的示例:

NSArray *menuArray = @[
   @{ @"Title" : @"Main Menu", @"Controller" : @"EntryViewController"},
   @{ @"Title" : @"States Lookup", @"Controller" : @"AllStatesViewController"},
   @{ @"Title" : @"Favorites", @"Controller" : @"FavoritesViewController"},
   @{ @"Title" : @"Help", @"Controller" : @"HelpViewController"},
   @{ @"Title" : @"About", @"Controller" : @"AboutViewController"},
];

通过这种方式,您甚至可以在字典中为订单添加一个额外的键,这样,如果您稍后需要在菜单中插入项目,您可以稍后对其进行排序。

关于ios - 使用自定义顺序对 NSArray 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20475593/

相关文章:

ios - 在 RxSwift 中订阅 Observable 或 Driver 花费的时间太长

ios - UIWebView和URLRequest拦截

ios - UITableView titleForHeaderInSection 未返回正确的 stringWithFormat

ios - 具有 "might"为 nil 的对象的 NSArray

ios - 添加其他对象到 NSArray

ios - xcode - 从下到上的 TableView 行

ios - 页面 View Controller 未按照其编码的样式进行转换

ios - 检查当前响应者?

ios - 具有警报级别的 UIWindow 位于状态栏级别之上

ios - 如何在 Ordered To-Many 关系中重复项目?