2009-08-29 143 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; 
}