1

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

在下面的示例中,如果我为未排序数组中的每个对象打印出“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
4

3 回答 3

4

您可以使用sortUsingComparator:NSMutableArray 中的函数。如果 order 仅取决于 '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;
        }];
于 2013-08-23T12:16:53.027 回答
1

您可以通过以下方式轻松做到这一点:

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(id obj1, id obj2) {
    //Here you can return NSOrderedSame, NSOrderedAscending or NSOrderedDescending 
    //based on your logic
}];
于 2013-08-23T12:16:07.410 回答
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;
}];
于 2013-08-23T12:20:50.570 回答