2014-04-14 163 views
0

我有一個存儲學生ID作爲鍵的字典,以及它們的顯示名稱作爲名爲「display」的子字典的鍵。該詞典是這個樣子:按值(非關鍵字)按字母順序排序NSMutableDictionary

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數組時引發錯誤。

如果有人能幫助我或指出我朝着正確的方向,那將不勝感激。謝謝!

+0

我不認爲你可以使用'NSSortDescriptor'和'NSString'數組。考慮使用'NSArray'的'sortedArrayUsingSelector'方法。 – user3386109

+0

我如何對兩個數組排序,以便鍵和對象一旦排序就匹配起來? – user3529561

+1

**有什麼錯誤使它「投擲」??? ** –

回答

1

你必須根據它們鏈接到字典中的值排序鍵數組,然後創建第二個數組,雖然我覺得你並不需要第二個數組。實現要在NSMutableArray使用sortUsingComparator:方法是什麼,這樣的一種方法:

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

希望它能幫助。

+0

非常感謝,作品像一個魅力。將永遠無法自己弄清楚。 – user3529561