iOS 自定义对象数组排序 自定义对象某属性排序

文章翻译自stackoverflow问题‘How to sort an NSMutableArray with custom objects in it?

原问题链接http://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it

以下是正文:

数组排序我们经常用到,有时候可能需要做一些比较特殊的排序。比如说我的数组中装了一些我自定义的对象,要运用对象里面的某一个属性进行排序。文章以一个'MYPerson'类,按照里面的‘birthDate’属性进行排序,该属性是‘NSDate’类。需要说明的是,系统已经实现了NSDate类时间的排序方法:

    NSDate *date1 = [NSDate date];
    NSDate *date2 = [NSDate dateWithTimeIntervalSinceNow:5];
    NSComparisonResult result = [date1 compare:date2];
//    typedef NS_ENUM(NSInteger, NSComparisonResult) {
//    NSOrderedAscending = -1L, 升序
//    NSOrderedSame,    相同
//    NSOrderedDescending};   降序
首先我们自定义一个MYPerson类,然后重写一下初始化方法方便初始化的时候赋值生日属性。然后采用随机数的办法生成一定个数,生日时间随机的对象:

    //随机生成模拟初始数据
    NSMutableArray<MYPerson *> *originArray = @[].mutableCopy;
    for (int index = 0; index < 10; index++) {
        
        NSInteger random = arc4random() % 99;
        NSDate *date = [NSDate dateWithTimeIntervalSinceNow:random * 100000];
        MYPerson *person = [[MYPerson alloc] initWithBirthDate:date];
        [originArray addObject:person];
        NSLog(@"第%d个:%@", index, date);
    }


列了三种排序的方法。

方法1为:Compare method    在自定义的对象中实现compare方法,然后数组利用选择器直接排序。自定义类中实现如下


然后调用方法进行排序

 [originArray sortedArrayUsingSelector:@selector(compare:)];

方法2为:NSSortDescriptor(better) 比前者要好写  该类时专门用来描述数组排序的规则的。用KVC的方法生成实例对象,需要注意的是,原自定义对象的属性作为key生成该排序描述对象的时候,这个key一定不能写错,不然会造成程序出错。实现方法如下:

#pragma mark 方法2.NSSortDescriptor(better)
- (NSArray *)sortedWithNSSortDescriptor:(NSArray *)originArray {

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate" ascending:YES];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    return [originArray sortedArrayUsingDescriptors:sortDescriptors];
}

方法3为:Blocks(shiny!) 答主推荐的方法 用NSArray自带的block进行排序,有点是代码都在一块,简洁明了。实现如下:

    #pragma mark 方法3.Blocks(shiny!)
    NSArray *sortedArray3 = [originArray sortedArrayUsingComparator:^NSComparisonResult(MYPerson *personA, MYPerson *personB) {
       
        return [personA.birthDate compare:personB.birthDate];
    }];

因为刚好是时间要进行对比,所以compare方法已经实现好了, 如果是其他类型的有自己需要的对比规则也是可以实现的。 


******以上

(欢迎随手给一颗星星哦~)本篇博客Demo地址https://github.com/xmy0010/DemoForCSDN

本人邮箱[email protected]欢迎小伙伴一起讨论,学习,进步。




猜你喜欢

转载自blog.csdn.net/xmy0010/article/details/53839115