2012-09-30 48 views
2

我有以下鍵值排序的NSArray以升序

密鑰的NSdictonary對象:1.infoKey,2.infoKey,3.infoKey,4.infoKey,5.infoKey,6.infoKey,7.infoKey ,8.infoKey,9.infoKey,10.infoKey,11.infoKey

注意它們沒有排序,可以按任意順序排列,即3.infoKey,7.infoKey,2.infoKey等

我我試圖做的是排序的關鍵值,即1,2,3,4,5,6,7,8,9,10,11 ....這是我迄今使用的代碼,但每次我做一種排序,它排序,我不想(見下文)

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
     NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"talkBtns.plist"]; 

     NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] initWithContentsOfFile:stringsPlistPath]; 


     NSArray *myKeys = [dictionary2 allKeys]; 

//This didn't give the right results 
     //sortedKeys = [myKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)]; 

//This didn't give the right results either 
     NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; 
     sortedKeys = [myKeys sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]]; 

    // *********** 
     // GET KEY VALUES TO 
     // LOOP OVER 
     // *********** 
     /* */ 
     for (int i = 0; i < [sortedKeys count]; i++) 
     { 
      NSLog(@"[sortedKeys objectAtIndex:i]: %@", [sortedKeys objectAtIndex:i]); 
     } 

    //output I get 
    [sortedKeys objectAtIndex:i]: 1.infoKey 
    [sortedKeys objectAtIndex:i]: 10.infoKey 
    [sortedKeys objectAtIndex:i]: 11.infoKey 
    [sortedKeys objectAtIndex:i]: 2.infoKey 
    [sortedKeys objectAtIndex:i]: 3.infoKey 
    [sortedKeys objectAtIndex:i]: 4.infoKey 
    [sortedKeys objectAtIndex:i]: 5.infoKey 
    [sortedKeys objectAtIndex:i]: 6.infoKey 
    [sortedKeys objectAtIndex:i]: 7.infoKey 
    [sortedKeys objectAtIndex:i]: 8.infoKey 
    [sortedKeys objectAtIndex:i]: 9.infoKey 

我試過兩種方法,他們都給出了相同的結果。我搜索了堆棧溢出和谷歌的每個地方,但找不到適合我的需求。

有什麼建議嗎?

+0

以下是你需要什麼:看到這個職位] [1] [1]:http://stackoverflow.com/questions/9943970/nssortdescriptor-sort-with-number- as-string – Guru

回答

10

您應該可以使用sortedArrayUsingComparatoroptions:NSNumericSearch對它進行排序,以便按照實際的數字順序進行排序,因爲10在嚴格按字母排序的排序中位於2之前;

NSArray * sortedKeys = 
    [myKeys sortedArrayUsingComparator:^(id string1, id string2) { 
     return [((NSString *)string1) compare:((NSString *)string2) 
             options:NSNumericSearch]; 
}]; 
+0

完美答案。感謝您在這篇文章的5分鐘內回覆! –