按特定顺序排序自定义对象

时间:2013-08-23 12:10:47

标签: ios objective-c nsmutablearray

我正试图找出一种基于我定义的自定义排序方案在数组中排序对象的整洁方法。

在下面的示例中,如果我打印出未排序数组中每个对象的“someText”值,那么我想要的输出就是。

  

- >牛    - >牛    - >猪    - >狗

实现此自定义排序的最佳选择是什么?

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

3 个答案:

答案 0 :(得分:4)

您可以在NSMutableArray中使用sortUsingComparator:函数。如果订单仅依赖于'someText'值,则天真实现可能如下所示:

[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;
        }];

答案 1 :(得分:1)

您可以通过以下方式轻松完成:

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

答案 2 :(得分: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;
}];