objective-c 如何按字母顺序对 NSArray 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1351182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 22:08:32  来源:igfitidea点击:

How to sort a NSArray alphabetically?

objective-csorting

提问by DotSlashSlash

How can I sort an array filled with [UIFont familyNames]into alphabetical order?

如何[UIFont familyNames]按字母顺序对填充的数组进行排序?

回答by Thomas Zoechling

The simplest approach is, to provide a sort selector (Apple's documentationfor details)

最简单的方法是,提供一个排序选择器(Apple 的文档了解详情)

Objective-C

目标-C

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

Swift

迅速

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


Apple provides several selectors for alphabetic sorting:

Apple 提供了几个用于字母排序的选择器:

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

Swift

迅速

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

Reference

参考

回答by JP Hribovsek

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:)This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

此处提供的其他答案提到使用@selector(localizedCaseInsensitiveCompare:)This 适用于 NSString 数组,但是,如果您想将其扩展到另一种类型的对象,并根据“名称”属性对这些对象进行排序,则应改为执行此操作:

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

Your objects will be sorted according to the name property of those objects.

您的对象将根据这些对象的名称属性进行排序。

If you want the sorting to be case insensitive, you would need to set the descriptor like this

如果您希望排序不区分大小写,则需要像这样设置描述符

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

回答by Ben G

A more powerful way of sorting a list of NSString to use things like NSNumericSearch :

对 NSString 列表进行排序以使用诸如 NSNumericSearch 之类的更强大的方法:

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

Combined with SortDescriptor, that would give something like :

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

回答by Jayprakash Dubey

Use below code for sorting in alphabetical order:

使用以下代码按字母顺序排序:

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

Below is console log :

以下是控制台日志:

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
)

回答by Lisarien

Another easy method to sort an array of strings consists by using the NSString descriptionproperty this way:

另一种对字符串数组进行排序的简单方法是通过description这种方式使用 NSString属性:

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

回答by narco

This already has good answers for most purposes, but I'll add mine which is more specific.

对于大多数目的,这已经有了很好的答案,但我会添加我的更具体的答案。

In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".

在英语中,通常当我们按字母顺序排列时,我们会忽略短语开头的单词“the”。所以“美国”将在“U”而不是“T”下排序。

This does that for you.

这为您做到了。

It would probably be best to put these in categories.

最好将这些分类。

// 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;
}

回答by deepa

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