zoukankan      html  css  js  c++  java
  • NSMutable sort排序

    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;

            };

  • 相关阅读:
    asp.net中插件开发模式说明
    Url路径重写的原理
    Linux上搭建各种环境(一)
    常见Post提交数据方式接口测试
    Jmeter4.0----CSV Data Set Config_使用表格进行参数化(22)
    弱网测试----App
    性能测试基础
    使用fiddler实现手机抓包
    Jmeter4.0----发送邮箱之SMTP Sampler(21)
    Jmeter4.0----发送测试结果到邮箱之邮件观察仪(20)
  • 原文地址:https://www.cnblogs.com/likwo/p/3983664.html
Copyright © 2011-2022 走看看