码迷,mamicode.com
首页 > 移动开发 > 详细

iOS自定义model排序

时间:2016-09-26 20:02:10      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

在开发过程中,可能需要按照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排序

标签:

原文地址:http://www.cnblogs.com/jukaiit/p/5910194.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!