首页 > 代码库 > iOS自定义model排序

iOS自定义model排序

在开发过程中,可能需要按照model的某种属性排序。

1、自定义model

@interface Person : NSObject@property (nonatomic,copy) NSString *name;@property (nonatomic,assign) int age;@end

2、创建model对象

       //创建model        Person *liming = [[Person alloc] init];        liming.name = @"liming";        liming.age = 18;                        Person *zhangjie = [[Person alloc] init];        zhangjie.name = @"zhangjie";        zhangjie.age = 20;                Person *liuxin = [[Person alloc] init];        liuxin.name = @"liuxin";        liuxin.age = 17;                Person *wanghua = [[Person alloc] init];        wanghua.name = @"wanghua";        wanghua.age = 16;    

3、创建存储数组

        //创建存储数组        NSMutableArray *personArray = [NSMutableArray array];        [personArray addObject:liming];        [personArray addObject:zhangjie];        [personArray addObject:liuxin];        [personArray addObject:wanghua];        

4、按model年龄属性 排序

        //model 按年龄属性 排序        NSArray *ageSortResultArray = [personArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {                        Person *per1 = obj1;                        Person *per2 = obj2;                        if (per1.age > per2.age) {                return NSOrderedDescending;//降序            }else if (per1.age < per2.age)            {                return NSOrderedAscending;//升序            }else            {                return NSOrderedSame;//相等            }                    }];    

5、打印结果

         //打印结果        for (Person *per in ageSortResultArray) {            NSLog(@"per.age = %d",per.age);        }

6、截图

技术分享

iOS自定义model排序