1. 程式人生 > >iOS開發中對陣列元素進行排序

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