zoukankan      html  css  js  c++  java
  • 排序的几种方法 oc

    NSArray *arr = @[
                             @"234",
                             @"123",
                             @"235",
                             @"133"
                             ];
            NSArray *sortArr = [arr sortedArrayUsingSelector:@selector(compare:)];
            NSLog(@"%@",sortArr);//用要排序的原数组调用实例方法,第二个参数,是方法选择,如果数组的元素都是字符串,那么直接用compare:就行
     
            //block(代码块)排序
            NSArray *sortArr2 = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
                return [obj1 compare:obj2];//根据比较结果,如果结果是1,则交换
            }];
     
            NSLog(@"%@",sortArr2);
    main函数
     Student *s = [[Student alloc] init];
            s.name = @"zhangyu";
            s.age = 20;
           
            Student *s1 = [[Student alloc] init];
           
            s1.name = @"zhangyuzi";
            s1.age = 18;
           
            Student *s2 = [[Student alloc] init];
            s2.age = 21;
            s2.name = @"lirongsheng";
           
            NSArray *arr = @[
                             s,
                             s1,
                             s2
                             ];
           
           
            //自定义对象排序
            NSArray *stuArr = [arr sortedArrayUsingSelector:@selector(compareWithAge:)];
            NSLog(@"%@",stuArr);
        }
        return 0;
    }
    main.h
    #import <Foundation/Foundation.h>

    @interface Student : NSObject

    @property (nonatomic, strong) NSString *name;
    @property (nonatomic, assign) int age;

    //自定义比较方法(排序时调用),要遵循compare:方法
    //格式:-(NSComparisonResult)方法名:(要比较的类名 *)参数名

    -(NSComparisonResult)compareWithName:(Student *)stu;

    -(NSComparisonResult)compareWithAge:(Student *)stu;
    @end
    main.m
    #import "Student.h"

    @implementation Student

    -(NSString *)description{
        return [NSString stringWithFormat:@"%@,%d",_name,_age];
    }

    //比较方法的实现
    -(NSComparisonResult)compareWithName:(Student *)stu{
        //对象的比较结果就相当于属性比较结果,self,最开始代表第0个元素,后面再比较时,代表交换后的满足条件的对象
        /*
         0  self a[0];
         1  self a[1]
         2  self a[2]
         */
        //当self放在第一个参数是,代表升序,放在第二个参数时,代表降序    只有result为1的时候才进行交换
        NSComparisonResult result = [stu.name compare: self.name];
       
        return result;
    }

    -(NSComparisonResult)compareWithAge:(Student *)stu{
        NSComparisonResult result;
       
        if (self.age < stu.age) {
            result = 1;
        }else{
            result = -1;
        }
       
        return  result;
    }
    @end
  • 相关阅读:
    算法总结之 两个链表生成相加链表
    算法总结之 复制含有随机指针节点的链表
    算法总结之 将单向链表按某值划分成左边小、中间相等、右边大的形式
    在PHP5.3以上版本运行ecshop和ecmall出现的问题及解决方案
    windows下配置nginx+php环境
    ecmall程序结构图与数据库表分析
    ecmall数据字典
    Ecmall二次开发-增删改查操作
    PHP7:10件事情你需要知道的
    PHP命名空间规则解析及高级功能3
  • 原文地址:https://www.cnblogs.com/zhangyu666666/p/4931124.html
Copyright © 2011-2022 走看看