按值(不是键)按字母顺序对NSMutableDictionary进行排序

时间:2014-04-14 22:39:00

标签: objective-c sorting nsmutabledictionary

我有一个字典,用于存储学生ID作为键,以及它们的显示名称作为名为“display”的子字典的键。字典看起来像这样:

id-1:
  display: mark
id-2:
  display: alexis
id-3:
  display: beth

我希望列表分为两个数组,一个用于键,一个用于值,看起来像这样

key   value
id-2  alexis
id-3  beth
id-1  mark

我目前有这段代码:

-(void)alphabetize {
    PlistManager *pm = [[PlistManager alloc] init];
    NSMutableDictionary *students = [pm getStudentsDict:ClassID];;
    NSMutableArray *keyArray = [[NSMutableArray alloc] init];
    NSMutableArray *valArray = [[NSMutableArray alloc] init];

    for (id key in students) {
        [keyArray addObject:key];
        [valArray addObject:[[students objectForKey:key] objectForKey:@"display"]];
    }

    NSSortDescriptor *alphaDescriptor = [[NSSortDescriptor alloc] initWithKey:@"DCFProgramName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
    NSArray *sortedValues = [valArray sortedArrayUsingDescriptors:[NSMutableArray arrayWithObjects:alphaDescriptor, nil]];
    NSLog(@"%@", sortedValues);
}

但在创建sortedValues数组时会抛出错误。

如果有人能帮助我或指出我正确的方向,那将非常感激。谢谢!

1 个答案:

答案 0 :(得分:1)

你必须根据它们在字典中链接的值对键数组进行排序,然后创建第二个数组,尽管我觉得你并不真的需要第二个数组。实现目标的一种方法是使用sortUsingComparator:中的NSMutableArray方法,如下所示:

PlistManager *pm = [[PlistManager alloc] init];
NSMutableDictionary *students = [pm getStudentsDict:ClassID];
NSMutableArray *sortedKeys = [[students allKeys] mutableCopy]; // remember to manually release the copies you create
[sortedKeys sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSString *student1 = [students objectForKey:obj1];
    NSString *student2 = [students objectForKey:obj2];
    return [student1 compare:student2]; // this does a simple comparison, look at the NSString documentation for more options
}];
// at this point your sortedKeys variable contains the keys sorted by the name of the student they point to //
// if you want to create the other array you can do so like this:
NSArray *sortedStudents = [students objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];

// you can also iterate through the students like so:
for (int i = 0; i < sortedKeys.count; ++i)
{
    NSString *key = sortedKeys[i];
    NSString *student = [students objectForKey:key];
}

// or access directly:
NSString *studentAtIndex3 = [students objectForKey:sortedKeys[3]];

// always remember to release or autorelease your copies //
[sortedkeys release];

希望它有所帮助。