我有一个包含自定义对象的数组,该对象具有名为 seat
的属性。座位可以有值 1A、1D、1C、1k、2A、2k、2D、2C。
现在可以随意排列了,我想按类(class)排序,但是排序只考虑座位数值,不考虑A、C、D、K。
我希望顺序为 1A、1C、1D、1K 等等。
这是我在 SeatDO 对象中实现的:
-(NSComparisonResult) compareBySeatNumber:(SeatDO*)other {
NSComparisonResult result = NSOrderedSame;
NSInteger seatNumber = [self.seat integerValue];
NSInteger otherSeatNumber = [other.seat integerValue];
if (seatNumber > otherSeatNumber) {
result = NSOrderedDescending;
} else if (seatNumber < otherSeatNumber) {
result = NSOrderedAscending;
}
return result;
}
如何让它也考虑这些字母......?
最佳答案
假设您将座位号转换为 NSString
NSArray *sortedSeats = [seats sortedArrayUsingSelector:@selector(localizedStandardCompare:)]
应该可以解决问题。对字符串进行排序自然会按照您需要的排序顺序进行。
否则你可以在比较时只使用字符串
[seats sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 stringValue] localizedStandardCompare:[obj2 stringValue]];
}];
我假设 stringValue
可用于您的自定义对象。如果没有,只需将其替换为任何将返回实例的 NSString
描述的内容。
注意
正如 Alladinian 所建议的,您希望使用 localizedStandardCompare:
而不是 caseInsensitiveCompare:
,以便获得正确的词典顺序。
关于iphone - 如何根据此属性对自定义对象数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17163379/