星空网 > 软件开发 > 操作系统

NSSortDescriptor对象进行数组排序

//创建一个数组

    NSArray *array = @[@"zhangsan", @"lisi", @"zhonger", @"zhubada", @"honghunag"];

    //创建一个排序条件,也就是一个NSSortDescriptor对象

    //其中第一个参数为数组中对象要按照什么属性来排序(比如自身、姓名,年龄等)

    //第二个参数为指定排序方式是升序还是降序

    //ascending  排序的意思,默认为YES 升序

    NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];

    NSArray *newArray = [array sortedArrayUsingDescriptors:@[des]];

    NSLog(@"%@",newArray);

 

   可以实现第一排序条件和第二排序条件

    创建一个Person类

    Person *p1 = [[Person alloc] initWithName:@"zhonger" age:@"19"];

    Person *p2 = [[Person alloc] initWithName:@"zhubada" age:@"11"];

    Person *p3 = [[Person alloc] initWithName:@"zhubada" age:@"1"];

    Person *p4 = [[Person alloc] initWithName:@"zhubada" age:@"33"];

    Person *p5 = [[Person alloc] initWithName:@"hehehe" age:@"38"];

    NSArray *person = @[p1, p2, p3, p4, p5];

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

    NSSortDescriptor *des2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];

    NSArray *newArray1 = [person sortedArrayUsingDescriptors:@[des1,des2]];

    NSLog(@"%@",newArray1);

    /*

     使用NSSortDesriptor进行数组排序有三步

     1.创建一个用来排序的数组

     2.创建一个排序条件,初始化中需要指定按照数组中对象的什么属性进行排序,升序或者降序

     3.数组根据排序条件进行排序,得到一个排序之后的数组(如果是可变数组,不会生成新数组,还是本身)

     */

    使用的sortedArrayUsingSelecor:的方法,就不需要创建NSSortDescriptor

    NSArray *strArray = @[@"zhonger", @"zhubada", @"qiuxiang", @"tangbohu", @"honghuang"];

    NSArray *nesStr = [strArray sortedArrayUsingSelector:@selector(compare:)]; //SEL  只能用@selector(方法名)给定,并且,如果数组使用这个数组进行排序,此方法必须是返回值为NSComparisionResult

    NSLog(@"newStr is %@",nesStr);

 

    NSArray *personNewArray = [person sortedArrayUsingSelector:@selector(compareByName:)];

    NSLog(@"--%@",personNewArray);




原标题:NSSortDescriptor对象进行数组排序

关键词:ip

ip
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

广州到澳大利亚专线:https://www.goluckyvip.com/tag/32117.html
广州到澳门专线:https://www.goluckyvip.com/tag/32118.html
广州到巴基斯坦专线:https://www.goluckyvip.com/tag/32119.html
广州到波兰专线:https://www.goluckyvip.com/tag/32120.html
广州到俄罗斯专线:https://www.goluckyvip.com/tag/32121.html
广州到非洲空运:https://www.goluckyvip.com/tag/32122.html
在古巴做游轮 古巴旅游项目:https://www.vstour.cn/a/363194.html
西藏旅游攻略自驾游需要多少天 去西藏旅游自驾游要多久时间:https://www.vstour.cn/a/363195.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流