Objective c 目标C-对字符串数组进行排序
我必须根据对象的属性(即字符串)对对象数组进行排序。 我怎样才能做到这一点?您需要使用Objective c 目标C-对字符串数组进行排序,objective-c,arrays,string,sorting,Objective C,Arrays,String,Sorting,我必须根据对象的属性(即字符串)对对象数组进行排序。 我怎样才能做到这一点?您需要使用 -[NSArray sortedArrayUsingSelector:] 或 -[NSMutableArray sortUsingSelector:并将@选择器(比较:)作为参数传递 下面是答案的链接 以下是我最终使用的-效果非常好: [categoryArray sortedArrayWithOptions:0 usingComparator:^NSComparisonRes
-[NSArray sortedArrayUsingSelector:]
或
-[NSMutableArray sortUsingSelector:
并将@选择器(比较:)
作为参数传递
下面是答案的链接
以下是我最终使用的-效果非常好:
[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];
}];
[categoryArray SorterDarray WithOptions:0
使用比较器:^n比较结果(id obj1,id obj2)
{
id cat1=obj1;
id cat2=obj2;
返回[cat1.name比较:cat2.name选项:NSCaseInsensitiveSearch];
}];
SelectableCategory
只是一个定义类别及其所有属性和元素的@protocol SelectableCategory
协议。仅对字符串数组进行排序:
sorted = [array sortedArrayUsingSelector:@selector(compare:)];
对于使用键“name”对对象进行排序:
此外,您可以使用以下命令代替compare:
:
不区分大小写比较:
LocalizedCase不敏感比较:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
sorted = [array sortedArrayUsingDescriptors:@[sort]];