iphone - 如何根据此属性对自定义对象数组进行排序?

标签 iphone ios objective-c sorting

我有一个包含自定义对象的数组,该对象具有名为 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/

相关文章:

ios - 我是否需要 ios sdk 7.0 才能使用 swift 在 xcode 6 beta 中开发 ios 7 应用程序

ios - NSSet 以逗号分隔的字符串

iphone - 有人在将 Xcode3.2x 项目迁移到 Xcode4 时遇到问题吗?

iphone - 显示 UIMenuController 时获取选定的文本

ios - iPhone SDK : Opening a cell with a dedicated button, 不是通过细胞敲击

iphone - 当 dispatchPeriod 与 Google Analytics 一起使用时,我可以立即/手动调度事件吗?

iphone - 我必须执行哪些方法才能重新排列 UITableView 行?

iphone - iPhone:如何将“yyyyMMddThhmmss”格式字符串转换为NSDate?

ios - 如何将 4 个字节转换为来自 NSData 的 Objective-C 中的 float

ios - 如何为 subview Controller 设置 topLayoutGuide 位置