简体   繁体   English

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

[英]Sort an NSArray with custom order

I have an NSMutableDictionary object that contains a list of menu items for an iPhone app. 我有一个NSMutableDictionary对象,其中包含iPhone应用程序的菜单项列表。 The desired order of the menu items is not alphabetical so the standard way of sorting the keys is not really an option. 菜单项的所需顺序不是按字母顺序排列的,因此排序键的标准方法实际上不是一种选择。 My dictionary is as follows and is initialized in the desired order (I understand that dictionaries are not sorted--I need to sort the array of keys in this order): 我的字典如下,并按所需顺序初始化(我知道字典没有排序 - 我需要按此顺序对键数组进行排序):

    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"];

How can I get a list of keys and sort them in the same order as this dictionary ? 如何获取密钥列表并按照与此字典相同的顺序对其进行排序? Thanks! 谢谢!

You can't, NSDictionary does not save the order in which items are added. 你不能, NSDictionary不保存添加项目的顺序。 For this you should use a NSArray . 为此你应该使用NSArray

Here is an example of how you can us it: 以下是您如何使用它的示例:

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

This way you can even add an extra key in the dictionary for the order, so you can sort it later if you need to insert items later in the menu. 这样,您甚至可以在字典中为订单添加额外的键,因此如果您需要稍后在菜单中插入项目,可以稍后对其进行排序。

Create an array of keys and another of values. 创建一个键数组和另一个值。 Then use the dictionaryWithObjects:forKeys: method to create your dictionary. 然后使用dictionaryWithObjects:forKeys:方法创建字典。 Then you don't need to do any additional sorting because you have the array of keys. 然后你不需要做任何额外的排序,因为你有一组键。

As has been pointed out, you can't get the ordered keys back from the dictionary so you need to use the original array of keys for your order information. 正如已经指出的那样,您无法从字典中获取有序键,因此您需要使用原始数组键来获取订单信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM