iOS开发中对数组元素进行排序

直接上代码, 请看:

//
//  ViewController.m
//  数组排序
//
//  Created by Wangjunling on 16/4/12.
//  Copyright © 2016年 Wangjunling. All rights reserved.
//

#import "ViewController.h"
#import "Person.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self sortFunc1];
    [self sortFunc2];
    
}
//方法1
- (void)sortFunc1 {
     NSArray *arr = @[@2, @9, @334, @66, @5, @15];
    //1.使用系统的Compare方法
    NSArray *sortResultArr = [arr sortedArrayUsingSelector:@selector(compare:)];
    NSLog(@"%@", sortResultArr);
}
//方法2
- (void)sortFunc2 {
    Person *p1 = [Person new];
    p1.name = @"xiaohua5";
    p1.age = 18;
    p1.score = 99;
    Person *p2 = [Person new];
    p2.name = @"xiaohua8";
    p2.age = 18;
    p2.score = 88;
    Person *p3 = [Person new];
    p3.name = @"xiaohua6";
    p3.age = 17;
    p3.score = 77;
    NSArray *personArr = @[p1, p2, p3];
    //2.使用自定义的compare方法, 此方法为block形式,代码简洁直观
    NSArray *sortResultArr = [personArr sortedArrayUsingComparator:^NSComparisonResult(Person *obj1, Person *obj2) {
        NSComparisonResult result = [@(obj1.age) compare:@(obj2.age)];

        if (result == NSOrderedSame) {
            result = [obj1.name compare:obj2.name];
        }
        return result;
    }];
     NSLog(@"%@", sortResultArr);
}
//方法3 通过排序描述器排序, 此方法方便通过某个字段去比较, 在实际开发中最常见
- (void)sortFunc3 {
    Person *p1 = [Person new];
    p1.name = @"xiaohua5";
    p1.age = 18;
    p1.score = 99;
    Person *p2 = [Person new];
    p2.name = @"xiaohua8";
    p2.age = 18;
    p2.score = 88;
    Person *p3 = [Person new];
    p3.name = @"xiaohua6";
    p3.age = 17;
    p3.score = 77;
    NSArray *personArr = @[p1, p2, p3];
    //排序描述:即要排序的字段,
    NSSortDescriptor *descriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:true];
    //排序描述:即要排序的字段,
    NSSortDescriptor *descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"score" ascending:true];
    //Descriptors参数为数组, 放入要排序的字段, 系统会按照先后顺序排序,
    //上面的p1 p2 p3 先按照年龄排序, 年龄一样的在按照分数排序
    NSArray *sortResultArr = [personArr sortedArrayUsingDescriptors:@[descriptor1,descriptor2]];
    NSLog(@"%@", sortResultArr);
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end



你可能感兴趣的:(iOS之语法基础)