NSMutable sort排序

本文详细介绍了如何在Objective-C和Swift中为对象实现自定义比较方法,进而实现对象数组的排序。通过使用比较方法、NSSortDescriptor和块(block),可以轻松地按照一个或多个属性对对象数组进行排序。文章还提供了实例代码和说明,帮助开发者快速掌握排序技巧。

Compare method

Either you implement a compare-method for your object:

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];

NSSortDescriptor (better)

or usually even better:

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"birthDate"
                                              ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

You can easily sort by multiple keys by adding more than one to the array. Using custom comparator-methods is possible as well. Have a look at the documentation.

Blocks (shiny!)

There's also the possibility of sorting with a block since Mac OS X 10.6 and iOS 4:

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *first = [(Person*)a birthDate];
    NSDate *second = [(Person*)b birthDate];
    return [first compare:second];
}];

For this particular example I'm assuming that the objects in your array have a 'position' method, which returns an NSInteger.

NSArray *arrayToSort = where ever you get the array from... ;
NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {
  if ([obj1 position] > [obj2 position]) { 
    return (NSComparisonResult)NSOrderedDescending;
  }
  if ([obj1 position] < [obj2 position]) {
    return (NSComparisonResult)NSOrderedAscending;
  }
  return (NSComparisonResult)NSOrderedSame;
};
NSArray *sorted = [arrayToSort sortedArrayUsingComparator:sortBlock];

Note: the "sorted" array will be autoreleased.

If this 'position' is in NSDictory.

NSComparisonResult (^sortBlock)(id, id) = ^(id obj1, id obj2) {

            NSInteger p1= [((NSString*) [obj1 objectForKey:@"position"]) integerValue];

            NSInteger p2= [((NSString*) [obj2 objectForKey:@"position"]) integerValue];

            if (p1 > p2) {

                return (NSComparisonResult)NSOrderedDescending;

            }

            if (p1 < p2) {

                return (NSComparisonResult)NSOrderedAscending;

            }

            return (NSComparisonResult)NSOrderedSame;

        };

转载于:https://www.cnblogs.com/likwo/p/3983664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值