1

I'm trying to figure out a tidy way of ordering objects in an array based on a custom ordering scheme that I define.

In the example below if I printed out the "someText" values for each object in my unsorted array, my desired output would be.

->Cow ->Cow ->Pig ->Dog

What would be my best option to achieve this custom sorting?

NSArray  *scheme=@[@"Cow",@"Pig",@"Dog"];


@interface TestObject : NSObject

@property (strong, nonatomic) NSString *someText;

@end


@interface Test : NSObject

@property (strong, nonatomic) NSMutableArray *unSortedObjects;

@end

@implementation Test

-(void)setup
{
TestObject *t1=[Test alloc]init];
t1.someText=@"Dog";
[unSortedObjects addObject:t1];
TestObject *t2=[Test alloc]init];
t2.someText=@"Pig";
[unSortedObjects addObject:t2];
TestObject *t3=[Test alloc]init];
t3.someText=@"Cow";
[unSortedObjects addObject:t3];
t4.someText=@"Cow";
[unSortedObjects addObject:t4];

}



@end
1

3 Answers 3

4

You can use sortUsingComparator: function in NSMutableArray. If order depends only on 'someText' value then naive implementation may look like:

[panels_ sortUsingComparator:^NSComparisonResult(TestObject* obj1, TestObject* obj2) {
            NSArray  *scheme = @[@"Cow",@"Pig",@"Dog"];
            NSUInteger ix1 = [scheme indexOfObject:obj1.someText];
            NSUInteger ix2 = [scheme indexOfObject:obj2.someText];
            if (ix1 < ix2){
                return NSOrderedAscending;
            }
            else if (ix1 > ix2){
                return NSOrderedDescending;
            }
            return NSOrderedSame;
        }];
Sign up to request clarification or add additional context in comments.

2 Comments

This works. Curiously though I had to remove the "*" pointer types from the NSUInteger definitions because the compiler complained of pointer to integer conversion. Also, small typo for the benefit of future searchers: you have "obj1" defined twice. ThankYou!
Fixed typos, thank you for listing them, sorry for imprecise answer
1

You can easily do that with:

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
    //Here you can return NSOrderedSame, NSOrderedAscending or NSOrderedDescending 
    //based on your logic
}];

Comments

0
[unSortedObjects sortUsingComparator: ^(id obj1, id obj2) {
    if ([scheme indexOfObject:obj1] > [scheme indexOfObject:obj2]) {
        return (NSComparisonResult)NSOrderedDescending;
    }

    if ([scheme indexOfObject:obj1] < [scheme indexOfObject:obj2]) {
        return (NSComparisonResult)NSOrderedAscending;
    }

    return (NSComparisonResult)NSOrderedSame;
}];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.