简体   繁体   English

如何在此属性上对自定义对象数组进行排序?

[英]How do I sort an array of custom objects on this property?

I have an array containing custom objects with a property named seat . 我有一个包含自定义对象的数组,其属性名为seat Seat can have values 1A, 1D , 1C , 1k , 2A, 2k, 2D, 2C. 座椅可具有值1A,1D,1C,1k,2A,2k,2D,2C。

Now these can be arranged in any order, and I want to sort them according to class, however the sorting only accounts for the seats numeric value and not A, C, D,or K. 现在这些可以按任何顺序排列,我想根据类对它们进行排序,但是排序只考虑座位数值而不是A,C,D或K.

I want the order to be 1A,1C,1D,1K and so on. 我希望订单为1A,1C,1D,1K等。

This is what I have implemented in the SeatDO object: 这是我在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;
}

How do I make it consider the letters as well..? 我如何让它也考虑到这些字母..?

Assuming that you convert the seat numbers to NSString s 假设您将座位号转换为NSString

NSArray *sortedSeats = [seats sortedArrayUsingSelector:@selector(localizedStandardCompare:)]

should do the trick. 应该做的伎俩。 Sorting strings will naturally follow the sort order you need. 排序字符串自然会遵循您需要的排序顺序。

Otherwise you could just use strings during the comparison with 否则你可以在比较期间使用字符串

[seats sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 stringValue] localizedStandardCompare:[obj2 stringValue]];
}];

I assumed that stringValue is available for you custom object. 我假设stringValue可用于您的自定义对象。 If not, simply replace it with anything that will return a NSString description of your instances. 如果没有,只需将其替换为将返回实例的NSString描述的任何内容。

NOTE 注意

As suggested by Alladinian, you want to use localizedStandardCompare: as opposed to caseInsensitiveCompare: , in order to the get the proper lexicographic order. 正如Alladinian所建议的那样,你想使用localizedStandardCompare:而不是caseInsensitiveCompare: ,以便获得正确的字典顺序。

Use localizedStandardCompare: as the selector (Finder-like sorting) 使用localizedStandardCompare:作为选择器(类似Finder的排序)

[seats sortedArrayUsingSelector:@selector(localizedStandardCompare:)]

While caseInsensitiveCompare: might seem like correct, if you add a @"10D" or @"01C" seat it would appear in front of all others... 虽然caseInsensitiveCompare:看起来似乎是正确的,如果你添加@"10D"@"01C"座位,它会出现在所有其他人面前......

如果您正在使用NSArray,您可以使用sortedArrayUsingSelector:(SEL)比较器对其进行排序,它将返回另一个已排序的数组

NSArray *arraySorted = [myArray sortedArrayUsingSelector:@selector(compareBySeatNumber:)];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM