zoukankan      html  css  js  c++  java
  • Object-C-Foundation-数组排序

    系统类型排序;

    NSArray *goodsNames =@[@"computer",@"iphone",@"ipad"];

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

    自定义排序

    Person *p1=[[Person alloc]initWithName:@"tom" andAge:12 andCard:nil];

    Person *p2=[[Person alloc]initWithName:@"jack" andAge:23 andCard:nil];

    Person *p1=[[Person alloc]initWithName:@"maggie" andAge:11 andCard:nil];

     NSArry *personsArray=@[p1,p2,p3];

    在person类中定义一个comparePerson方法

    /***************************************************************

    -(NSComparisonResult)comparePerson:(Person *)person

    {

        NSNumber *age1=[[NSNumber alloc]initWithInt:self.age];

        NSnumber *age2=[[NSNumber alloc]initWithInt:person.age];

        NSComparisonResult result=[age1 compare:age2];

      if(result == NSOrderedSame)

        {

             result=[self.name compare:person.name];

        }

        return result;

    }

    /******************************************************************

    NSArray *personsArray=@[p1,p2,p3];

    NSArray *sortedArray=[personsArray sortedArrayUsingSelector:@selector(comparePerson:)];

    完成对personsArray进行排序

    使用block进行排序

    NSArray *sortedArray=[personsArray sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){

         Person *p1=(Person *)obj1;

         Person *p2=(Person *)obj2;

         NSNumber *age1=[[NSNumber alloc]initWithInt:self.age];

        NSnumber *age2=[[NSNumber alloc]initWithInt:person.age];

        NSComparisonResult result=[age1 compare:age2];

      if(result == NSOrderedSame)

        {

             result=[self.name compare:person.name];

        }

        return result;

    }

    复杂排序

    NSSortDescriptor

    NSSortDescriptor *sort1=[[NSSortDescriptor]initWithKey:@"name" ascending:YES];

    NSSortDescriptor *sort2=[[NSSortDescriptor]initWithKey:@"age" ascending:YES];

    NSArray *conditionsArray=@[sort1,sort2];

    NSArray *sortedArray =[personsArray sortedArrayUsingDescriptors:conditionsArray];

    /*******************

    NSSortDescriptor *sort1=[[NSSortDescriptor]initWithKey:@"name" ascending:YES];

    NSSortDescriptor *sort2=[[NSSortDescriptor]initWithKey:@"self.card.balance" ascending:YES];

  • 相关阅读:
    STS IDE 个性化修改
    tomcat发布web项目,支持域名
    执行 maven 命令 报错Unable to add module to the current project as it is not of packaging type 'pom'[转]
    从数组中返回最大长度的所有子数组
    springboot 1.5.x 使用tomcat8设置cookie的domain以dot开头报错
    tomcat服务器配置字符集为utf-8-彻底解决中文乱码问题
    通配符的匹配很全面, 但无法找到元素 'mvc:annotation-driven' 的声明
    Java原理之HashMap
    你应该知道的JAVA面试题
    sql 置顶功能的查询
  • 原文地址:https://www.cnblogs.com/Opaser/p/4555066.html
Copyright © 2011-2022 走看看