【发布时间】:2011-08-14 19:50:01
【问题描述】:
我必须按对象的属性(即字符串)对对象数组进行排序。 我该怎么做?
【问题讨论】:
标签: objective-c arrays string sorting
我必须按对象的属性(即字符串)对对象数组进行排序。 我该怎么做?
【问题讨论】:
标签: objective-c arrays string sorting
你需要使用
-[NSArray sortedArrayUsingSelector:]
或
-[NSMutableArray sortUsingSelector:] 并将@selector(compare:) 作为参数传递。
【讨论】:
仅对字符串数组进行排序:
sorted = [array sortedArrayUsingSelector:@selector(compare:)];
使用键“name”对对象进行排序:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(compare:)];
sorted = [array sortedArrayUsingDescriptors:@[sort]];
另外,您可以使用 compare: 代替:
caseInsensitiveCompare:
localizedCaseInsensitiveCompare:
【讨论】:
这是我最终使用的 - 就像一个魅力:
[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];
}];
SelectableCategory 只是一个 @protocol SelectableCategory <NSObject> 定义了包含其所有属性和元素的类别。
【讨论】: