Reputation: 12405
I have an array containing custom objects with a property named seat
. Seat can have values 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.
I want the order to be 1A,1C,1D,1K and so on.
This is what I have implemented in the SeatDO object:
-(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..?
Upvotes: 5
Views: 285
Reputation: 108151
Assuming that you convert the seat numbers to NSString
s
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. If not, simply replace it with anything that will return a NSString
description of your instances.
NOTE
As suggested by Alladinian, you want to use localizedStandardCompare:
as opposed to caseInsensitiveCompare:
, in order to the get the proper lexicographic order.
Upvotes: 7
Reputation: 35646
Use localizedStandardCompare:
as the selector (Finder-like sorting)
[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...
Upvotes: 3
Reputation: 862
if you're using an NSArray you can sort it using sortedArrayUsingSelector:(SEL)comparator and it will return you another array sorted
NSArray *arraySorted = [myArray sortedArrayUsingSelector:@selector(compareBySeatNumber:)];
Upvotes: -2