美文网首页
对数组进行排序

对数组进行排序

作者: 七叶5 | 来源:发表于2017-08-05 09:27 被阅读8次

    对于简单对象,及系统自带的,例如:NSString,NSNumber,NSMutableArray等可用sortedArrayUsingSelector或sortUsingSelector
    1.不可变数组

    NSArray *array1 = @[@"11",@"a",@"mm",@"ii",@"tr",@"oo",@"rt"];
    
    NSArray *sortArray = [array1 sortedArrayUsingSelector:@selector(compare:)];
            NSLog(@"sortArray = %@",sortArray);
    

    2.把数组一的值拷贝给给变数值二,可变数组

    NSMutableArray *array2 = [NSMutableArray arrayWithArray:array1];
    

    //可变数组排序,没有返回值.参数类型是SEL那么代表此参数是个方法

      [array2 sortUsingSelector:@selector(compare:)];
    NSLog(@"array2 = %@",array2);
    

    3.不可变 数组中存储复杂对象时

       Person *per1 = [Person personName:@"m淼淼" sex:@"女" age:18];
            Person *per2 = [Person personName:@"x香香" sex:@"女" age:22];
            Person *per3 = [Person personName:@"w王发" sex:@"男" age:32];
            Person *per4 = [Person personName:@"z张静" sex:@"女" age:20]; 
    NSArray *arr1 = @[per1,per2,per3,per4];    
    ```c
    //NSSortDescriptor *description1 = [NSSortDescriptor sortDescriptorWithKey:arr1 ascending:YES];数组arr1中存储的是复杂对象,是不可以使用sort方法进行排序的.因为compare只适用于系统的简单对象进行排序
    ```c
    NSSortDescriptor *description1 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
            NSArray *newArray1 = [arr1 sortedArrayUsingDescriptors:@[description1]];
            //遍历数组输出结果
            for (Person *p in newArray1) {
                NSLog(@"des1=%@", p);
            }
    

    4.定义可变数组,进行排序,按名字降序排序

    NSMutableArray *mArray = [NSMutableArray arrayWithArray:arr1];
            NSSortDescriptor *des2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
            [mArray sortedArrayUsingDescriptors:@[des2]];
            for (Person *p in mArray) {
                NSLog(@"%@des2", p);
    

    相关文章

      网友评论

          本文标题:对数组进行排序

          本文链接:https://www.haomeiwen.com/subject/kedilxtx.html