NSArary自定义对象排序 NSComparator, compare

reference from :http://mobile.51cto.com/hot-434804.htm

1.构建Person类

Person.h

@interface Person : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *surname;
@property (nonatomic, strong) NSDate *dateOfBirth;
@end

2. 初始化ObjSort对象排序功能,包含一个NSArray数组,数组元素为自定义Person

ObjSort.h

/**
 * 对NSArray自定义对象排序类
 */
@interface ObjSort : NSObject
-(void)personsSort_NSComparator;//NSComparator比较器
@end

ObjSort.m

@interface ObjSort()
@property (nonatomic, strong) NSMutableArray *personObjs;//存储了若干个Person类对象的数组
@end

@implementation ObjSort

/**
 * 初始化对象
 * 初始化NSMutableArray数组personObjs的初始内容, 包装Person类对象
 */
-(instancetype)init{
    self = [super init];
    if (self == nil) {
        return nil;
    }

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd/MM/yyyy"];

    Person *person[5];
    for(int i=0; i<5; i++){
        person[i] = [[Person alloc] init];
    }

    person[0].name = @"Smith";
    person[0].surname = @"John";
    person[0].dateOfBirth = [formatter dateFromString:@"03/01/1984"];

    person[1].name = @"Andersen";
    person[1].surname = @"Jane";
    person[1].dateOfBirth = [formatter dateFromString:@"16/03/1979"];

    person[2].name = @"Clark";
    person[2].surname = @"Anne";
    person[2].dateOfBirth = [formatter dateFromString:@"13/09/1995"];

    person[3].name = @"Smith";
    person[3].surname = @"David";
    person[3].dateOfBirth = [formatter dateFromString:@"19/07/1981"];

    person[4].name = @"Johnson";
    person[4].surname = @"Rose";
    person[4].dateOfBirth = [formatter dateFromString:@"22/02/1989"];

    if (_personObjs==nil) {
        _personObjs = [[NSMutableArray alloc] initWithCapacity:5];
    }
    for (int i=0; i<5; i++) {
        [_personObjs addObject:person[i]];
    }

    [self showPersons:_personObjs];
    return self;
}

/**
 * 日志打印输出当前NSArray内容
 */
-(void)showPersons:(NSArray *)array{
    Person *person;

    if (_personObjs == nil) {
        NSLog(@"nil");
    }

    for (int i =0; i< [array count]; i++) {
        person = [array objectAtIndex:i];
        if ([person isKindOfClass:[Person class]]) {
            NSLog(@"---Person %d---", i);
            NSLog(@"Name: %@", person.name);
            NSLog(@"Surname: %@", person.surname);
            NSLog(@"DateOfBirth: %@", person.dateOfBirth);
        }
        else{
            NSLog(@"Object in personObjs is not Person class object.");
        }
    }  NSLog(@"All person print over.\n\n");
}

方法一:NSComparator block + NSArray的 sortedArrayUsingSelector

在ObjSort中实现方法personsSort_NSComparator

/**
 * 采用NSComparator比较的排序方法
 */
-(void)personsSort_NSComparator{

    NSComparator sortBlock = ^(Person *p1 , Person *p2){
        NSComparisonResult r1 = [p1.name compare:p2.name];
        if(r1 != NSOrderedSame){
            return r1;
        }else {
            NSComparisonResult r2 = [p1.surname compare:p2.surname];
            if (r2 != NSOrderedSame)
                return r2;
            else
                return [p1.dateOfBirth compare:p2.dateOfBirth];
        }
    };
    NSArray *personList = [self.personObjs sortedArrayUsingComparator:sortBlock];
    NSArray *personList = [self.personObjs sortedArrayUsingSelector:@selector(compare:)];
    [self showPersons:personList];
}

方法二:利用对象的自定义方法compare:

Person.m中添加

-(NSComparisonResult)compare:(Person *)otherPerson{
    NSComparisonResult r1 = [self.name compare:otherPerson.name];
    if(r1 != NSOrderedSame){
        return r1;
    }else {
        NSComparisonResult r2 = [self.surname compare:otherPerson.surname];
        if (r2 != NSOrderedSame)
            return r2;
        else
            return [self.dateOfBirth compare:otherPerson.dateOfBirth];
    }
    return [self.name compare:otherPerson.name];
}

ObjSort.m中添加

/**
 * 采用自定义对象自定义函数compare进行NSArray排序
 */
-(void)personsSort_CustomCompare{
    NSArray *personList = [self.personObjs sortedArrayUsingSelector:@selector(compare:)];
    [self showPersons:personList];
}

在ObjSort.h中添加响应的接口

/**
 * 对NSArray自定义对象排序类
 */
@interface ObjSort : NSObject
-(void)personsSort_NSComparator;//NSComparator比较器
-(void)personsSort_CustomCompare;//对象自定义比较方法Compare
@end

最后,在main.m(排序调用处)添加

        ObjSort *objSort = [[ObjSort alloc] init];
        [objSort personsSort_NSComparator];

方法一结果

---Person 0---
Name: Smith
Surname: John
DateOfBirth: 1984-01-02 16:00:00 +0000
---Person 1---
Name: Andersen
Surname: Jane
DateOfBirth: 1979-03-15 16:00:00 +0000
---Person 2---
Name: Clark
Surname: Anne
DateOfBirth: 1995-09-12 16:00:00 +0000
---Person 3---
Name: Smith
Surname: David
DateOfBirth: 1981-07-18 16:00:00 +0000
---Person 4---
Name: Johnson
Surname: Rose
DateOfBirth: 1989-02-21 16:00:00 +0000
All person print over.

---Person 0---
Name: Andersen
Surname: Jane
DateOfBirth: 1979-03-15 16:00:00 +0000
---Person 1---
Name: Clark
Surname: Anne
DateOfBirth: 1995-09-12 16:00:00 +0000
---Person 2---
Name: Johnson
Surname: Rose
DateOfBirth: 1989-02-21 16:00:00 +0000
---Person 3---
Name: Smith
Surname: David
DateOfBirth: 1981-07-18 16:00:00 +0000
---Person 4---
Name: Smith
Surname: John
DateOfBirth: 1984-01-02 16:00:00 +0000
All person print over.

方法二结果

---Person 0---
Name: Smith
Surname: John
DateOfBirth: 1984-01-02 16:00:00 +0000
---Person 1---
Name: Andersen
Surname: Jane
DateOfBirth: 1979-03-15 16:00:00 +0000
---Person 2---
Name: Clark
Surname: Anne
DateOfBirth: 1995-09-12 16:00:00 +0000
---Person 3---
Name: Smith
Surname: David
DateOfBirth: 1981-07-18 16:00:00 +0000
---Person 4---
Name: Johnson
Surname: Rose
DateOfBirth: 1989-02-21 16:00:00 +0000
All person print over.

---Person 0---
Name: Andersen
Surname: Jane
DateOfBirth: 1979-03-15 16:00:00 +0000
---Person 1---
Name: Clark
Surname: Anne
DateOfBirth: 1995-09-12 16:00:00 +0000
---Person 2---
Name: Johnson
Surname: Rose
DateOfBirth: 1989-02-21 16:00:00 +0000
---Person 3---
Name: Smith
Surname: David
DateOfBirth: 1981-07-18 16:00:00 +0000
---Person 4---
Name: Smith
Surname: John
DateOfBirth: 1984-01-02 16:00:00 +0000
All person print over.
时间: 2024-10-12 18:17:40

NSArary自定义对象排序 NSComparator, compare的相关文章

C#自定义对象排序

数组对象Array有一个Sort方法(点击查看Sort方法的实现),专门是用来排序的,请看下图 如果我们想为自己的类添加一个排序,只需要继承IComparable接口,实现CompareTo方法就行: 调用CompareTo方法内部实现对象的比较,通过返回值确定对象的顺序 负数值,当前对象<参数对象 正数值,当前对象>参数对象 零,两个对象相等 下面我们就根据接口自定义自己的对象排序方式 1 class People:IComparable 2 { 3 public uint Age { ge

ht-7 对arrayList中的自定义对象排序

1 package com.iotek.set; 2 3 import java.util.ArrayList; 4 import java.util.Collections; 5 import java.util.Comparator; 6 import java.util.List; 7 /** 8 * 9 * 对ArrayList容器中的内容进行排序: ArrayList中存储多个Person对象(具有name,age,id属性), 10 * 要求按照年龄从小到大排序,年龄相等的话再按照名

Objective—C中的排序及Compare陷阱

campare陷阱 NSString有多个compare相关方法: - (NSComparisonResult)compare:(NSString *)string; - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask; - (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOption

TreeSet排序,存储自定义对象,自定义比较器示例

Set:无序,不可以重复元素. |--HashSet:数据结构是哈希表.线程是非同步的. 保证元素唯一性的原理:判断元素的hashCode值是否相同. 如果相同,还会继续判断元素的equals方法,是否为true. |--TreeSet:可以对Set集合中的元素进行排序. 底层数据结构是二叉树. 保证元素唯一性的依据:compareTo方法return 0. TreeSet排序的第一种方式:让元素自身具备比较性. 元素需要实现Comparable接口,覆盖compareTo方法. 也种方式也成为

TreeSet 比较器排序 自定义对象

package cn.itcast.day21.treeset2; import java.util.Comparator; import java.util.TreeSet; /* * TreeSet 按照自定义对象Student的姓名长度 比较器排序 * * 自然排序or比较器排序取决于,TreeSet的构造方法 * 无参构造:自然排序 * 有参构造: 比较器排序 * * TreeSet集合保证元素排序和唯一性的原理 * 唯一性:根据比较的返回是否是0来决定 * 排序: * A:自然排序(元

Java基础知识强化之集合框架笔记45:Set集合之TreeSet存储自定义对象并遍历练习1(自然排序)

1. TreeSet存储自定义对象并遍历练习1(自然排序): (1)Student.java: 1 package cn.itcast_05; 2 3 /* 4 * 如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口 5 */ 6 public class Student implements Comparable<Student> { 7 private String name; 8 private int age; 9 10 public Student() { 11 super

Java基础知识强化之集合框架笔记46:Set集合之TreeSet存储自定义对象并遍历练习2(自然排序)

1. TreeSet存储自定义对象并遍历练习2: (1)Student.java 1 package cn.itcast_06; 2 3 /* 4 * 如果一个类的元素要想能够进行自然排序,就必须实现自然排序接口 5 */ 6 public class Student implements Comparable<Student> { 7 private String name; 8 private int age; 9 10 public Student() { 11 super(); 12

TreeSet的自然排序(自定义对象 compareTo方法)

>要实现自然排序,对象集合必须实现Comparable接口,并重写compareTo()方法 >一般需求中描述的是"主要条件",如:按姓名长度排序.  需注意次要条件 如:长度相同时,姓名内容,年龄等条件是否相等,这决定着是否存入TreeSet集合.   package cn.itcast.day21.treeset; /* * 要实现自然排序,就一定要实现Comparable接口,并重写compareTo()方法 * * 若不实现Comparable接口,而把对象往Tre

《java入门第一季》之TreeSet存储自定义对象并保证排序和唯一

上一篇用一个简单的例子,介绍了treeset集合存储的内部过程,这里再完善其存储自定义对象保证唯一. 需求:A: * 自然排序,按照年龄从小到大排序 *         B: * 成员变量值都相同即为同一个元素 自定义学生类给了出来: public class Student implements Comparable<Student> { private String name; private int age; public Student() { super(); } public St