2009-08-29 119 views

回答

687

最簡單的方法是,提供一種選擇(Apple's documentation的詳細信息)

目標C

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

夫特

let descriptor: NSSortDescriptor = NSSortDescriptor(key: "YourKey", ascending: true, selector: "localizedCaseInsensitiveCompare:") 
let sortedResults: NSArray = temparray.sortedArrayUsingDescriptors([descriptor]) 

蘋果提供了幾種選擇器字母排序:

  • compare:
  • caseInsensitiveCompare:
  • localizedCompare:
  • localizedCaseInsensitiveCompare:
  • localizedStandardCompare:

夫特

var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] 
students.sort() 
print(students) 
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" 

Reference

+5

文檔鏈接已過時,代碼示例不足以實際對數組進行排序。 localizedCaseInsensitiveCompare:需要以某種方式定義。 – 2010-12-20 15:40:54

+34

我更新了鏈接。感謝您指出了這一點。 localizedCaseInsensitiveCompare:是NSString的一個方法,應該足以對字符串數組進行排序。 – 2010-12-20 16:37:38

+1

這可以很容易地應用於包含任何自定義對象的數組(不僅僅是NSString)。您只需確保數組中的所有對象都實現了選擇器指定的消息。然後在這個消息裏面,你可以調用NSString比較你想要比較的對象的屬性。 – Luka 2012-06-22 18:00:13

264

這裏提供的其他的答案提及使用@selector(localizedCaseInsensitiveCompare :) 本作的NSString數組的偉大工程,但是如果你想要將其擴展到其他類型的對象,和排序這些對象根據「名稱」屬性,您應該這樣做:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; 
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]]; 

您的對象將根據這些對象的name屬性進行排序。

如果你想排序是不區分大小寫,您將需要設置描述這樣

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]; 
+13

+1,謝謝。有趣的是,這是比普遍接受的答案更常見的用例。 – 2012-11-23 05:27:07

+3

這種排序大寫字母,然後小寫字母 – HarshIT 2013-03-21 09:46:27

+0

我編輯我的答案,包括不區分大小寫排序 – 2013-08-09 17:28:55

25

排序的NSString的列表中使用的東西像NSNumericSearch的更強大的方法:

NSArray *sortedArrayOfString = [arrayOfString sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { 
      return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch]; 
     }]; 

與SortDescriptor相結合,即會看到這樣的:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES comparator:^NSComparisonResult(id obj1, id obj2) { 
     return [(NSString *)obj1 compare:(NSString *)obj2 options:NSNumericSearch]; 
    }]; 
NSArray *sortedArray = [anArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sort]]; 
1
-(IBAction)SegmentbtnCLK:(id)sender 
{ [self sortArryofDictionary]; 
    [self.objtable reloadData];} 
-(void)sortArryofDictionary 
{ NSSortDescriptor *sorter; 
    switch (sortcontrol.selectedSegmentIndex) 
    {case 0: 
      sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES]; 
      break; 
     case 1: 
      sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES]; 
      default: 
      break; } 
    NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil]; 
    [arr sortUsingDescriptors:sortdiscriptor]; 
    } 
+0

醜陋的格式是誠實的 – Mutawe 2016-08-31 05:56:49

10

使用以下代碼以字母順序排序:

NSArray *unsortedStrings = @[@"Verdana", @"MS San Serif", @"Times New Roman",@"Chalkduster",@"Impact"]; 

    NSArray *sortedStrings = 
    [unsortedStrings sortedArrayUsingSelector:@selector(compare:)]; 

    NSLog(@"Unsorted Array : %@",unsortedStrings);   
    NSLog(@"Sorted Array : %@",sortedStrings); 

下面是控制檯日誌:

2015-04-02 16:17:50.614 ToDoList[2133:100512] Unsorted Array : (
    Verdana, 
    "MS San Serif", 
    "Times New Roman", 
    Chalkduster, 
    Impact 
) 

2015-04-02 16:17:50.615 ToDoList[2133:100512] Sorted Array : (
    Chalkduster, 
    Impact, 
    "MS San Serif", 
    "Times New Roman", 
    Verdana 
) 
10

另一種簡單的方法進行排序字符串數組由通過使用的NSString description屬性這種方式:

NSSortDescriptor *valueDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES]; 
    arrayOfSortedStrings = [arrayOfNotSortedStrings sortedArrayUsingDescriptors:@[valueDescriptor]]; 
+0

這似乎有點無用;沒有理由以這種方式對字符串進行排序(並且可能會導致性能下降),對於其他對象,其描述屬性對於排序目的很少有用。 – mah 2018-02-18 22:31:23

0

這已經有很好的答案ose,但我會加我的更具體。

在英語中,通常當我們字母化時,我們忽略短語開頭的單詞「the」。所以「美國」將在「U」而不是「T」下訂購。

這是爲你做的。

這可能是最好把這些分類。

// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string. 

-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray { 

    NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) { 

     //find the strings that will actually be compared for alphabetical ordering 
     NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a]; 
     NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b]; 

     return [firstStringToCompare compare:secondStringToCompare]; 
    }]; 
    return sortedArray; 
} 

// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too. 

-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString { 
    NSString* result; 
    if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) { 
     result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]; 
    } 
    else { 
     result = originalString; 
    } 
    return result; 
}