I have an NSArray with values XS, S, M, L, XL, XXL in random order.
How would I go about sorting this properly in Objective-C?
I looked at this code for a starting point but I am having zero luck:
Sort a list by reference C#
If you create an ordered set to act as a "reference" order, you can then use the NSMutableSet method intersectSet: to create an ordered list from your array:
Edit David Rönnqvist just made a good point. Need to check for multiple instances of the same 'size'.
//This is my "reference" set, declared only once in my class
NSOrderedSet *reference = [NSOrderedSet orderedSetWithObjects:@"XS",@"S",@"M",@"L",@"XL", nil];
//This is the array I'm trying to sort, which may or may not contain all the sizes
NSArray *randomArray = [NSArray arrayWithObjects:@"XL", @"XS", @"M", @"XS", nil];
//Create a mutable ordered set from my reference
NSMutableOrderedSet *ordered = [NSMutableOrderedSet orderedSetWithOrderedSet:reference];
//Interset with the array
[ordered intersectSet:[NSSet setWithArray:randomArray]];
//Look for multiple instances of the same size
NSMutableArray *result = [NSMutableArray array];
for (NSString *sortedSize in ordered){
for (NSString *randomSize in randomArray){
if ([randomSize isEqualToString:sortedSize]){
[result addObject:randomSize];
}
}
}
My result from the above was an array containing:
@"XS", @"XS", @"M", @"XL"
If you were going to create a method that did this, you could also compare the count of ordered to the array you were sorting, and if they were equal don't bother with the iteration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With