从多维NSDictionary的子字典值创建排序数组

时间:2013-08-27 18:32:01

标签: ios objective-c nsmutablearray nsarray nsdictionary

我有一个包含子NSDictionaries的NSDictionary,我想知道是否可以按子字典的“名称”键的值按字母顺序对主字典进行排序。

NSDictionary *student1 = @{@"first_name" : @"Scott", @"last_name" : @"Smith"};
NSDictionary *student2 = @{@"first_name" : @"John", @"last_name" : @"Donalson"};
NSDictionary *student3 = @{@"first_name" : @"Mary", @"last_name" : @"Patricia"};
NSDictionary *student4 = @{@"first_name" : @"Zack", @"last_name" : @"Elliot"};

NSDictionary *students = @{"001": student1, "002": student2, "003": student3, "004": student4};

我希望能够创建一个只保存键的数组或可变数组,但是根据子词典中某些键的值进行排序。像这样:

last_name_array

["002", "004", "003", "001"];

first_name_array

["002", "003", "001", "004"];

1 个答案:

答案 0 :(得分:1)

查看NSDictionary方法keysSortedByValueUsingComparator:

您提供了一个比较器块,用于处理值(您的学生词典)并返回一组键。

https://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/doc/uid/20000140-SW21