Objective C - 对字符串数组进行排序

And*_*ino 19 arrays sorting string objective-c

我必须通过作为字符串的对象的属性对对象数组进行排序.我怎样才能做到这一点?

Jas*_*gun 37

你需要使用

-[NSArray sortedArrayUsingSelector:]
Run Code Online (Sandbox Code Playgroud)

要么

-[NSMutableArray sortUsingSelector:]@selector(compare:)作为参数传递.

这是答案的链接 排序日期字符串或对象的NSArray


Bor*_*rzh 9

仅用于排序字符串数组:

sorted = [array sortedArrayUsingSelector:@selector(compare:)];
Run Code Online (Sandbox Code Playgroud)

对于使用键"name"排序对象:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
sorted = [array sortedArrayUsingDescriptors:@[sort]];
Run Code Online (Sandbox Code Playgroud)

另外,compare:您可以使用:

  • caseInsensitiveCompare:

  • localizedCaseInsensitiveCompare:


cra*_*ned 7

这是我最终使用的 - 就像一个魅力:

[categoryArray sortedArrayWithOptions:0
               usingComparator:^NSComparisonResult(id obj1, id obj2)
{
    id<SelectableCategory> cat1 = obj1;
    id<SelectableCategory> cat2 = obj2;
    return [cat1.name compare:cat2.name options:NSCaseInsensitiveSearch];
}];
Run Code Online (Sandbox Code Playgroud)

SelectableCategory只是@protocol SelectableCategory <NSObject>定义类别及其所有属性和元素。