一个装了model的数组通过model 的属性排序

  • 在项目中有很多地方需要排序。
    今天在项目中遇到一个后台返回乱序的数据,但是移动端需要升序或降序排列。当然我首先想到的是冒泡排序,但是后面看了一个。其实还有种很简单的方法。code如下。

首先我们建立model

// .h文件中
@interface SortModel : NSObject

@property(nonatomic,strong) NSString *nameStr;
@property(nonatomic,strong) NSString *ageStr;
@property(nonatomic,assign) NSInteger age;

- (instancetype)initWithNameStr:(NSString *)nameStr ageStr:(NSString *)ageStr age:(NSInteger)age;
@end

// .m文件中
@implementation SortModel

- (instancetype)initWithNameStr:(NSString *)nameStr ageStr:(NSString *)ageStr age:(NSInteger)age{
    self = [super init];
    if (self){
        _nameStr = nameStr;
        _ageStr = ageStr;
        _age = age;
    }
    return self;
}
- (NSString *)description
{
    return [NSString stringWithFormat:@"model name is %@,model agestr is %@,model age is %ld", _nameStr,_ageStr,_age];
}
@end

然后我们来创建一个这个model 的数组

    SortModel *student1 = [[SortModel alloc] initWithNameStr:@"李涛" ageStr:@"26" age:24];
    SortModel *student2 = [[SortModel alloc] initWithNameStr:@"李涛1" ageStr:@"25" age:25];
    SortModel *student3 = [[SortModel alloc] initWithNameStr:@"李涛2" ageStr:@"24" age:26];
    NSArray *arr = @[student1,student2,student3];

最后我们来看看通过属性来排序吧

// ascending -> YES 为升序,NO为降序
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"_nameStr" ascending:NO];
//    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"_age" ascending:NO];
//    NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:@"_ageStr" ascending:YES];
    NSArray *sortedArr = [arr sortedArrayUsingDescriptors:@[sortDesc]];
    NSLog(@"sort arr is %@",sortedArr);

我们来看看控制台打印:
第一种为
"model name is \U674e\U6d9b2,model agestr is 24,model age is 26",
"model name is \U674e\U6d9b1,model agestr is 25,model age is 25",
"model name is \U674e\U6d9b,model agestr is 26,model age is 24"
第二种为
"model name is \U674e\U6d9b2,model agestr is 24,model age is 26",
"model name is \U674e\U6d9b1,model agestr is 25,model age is 25",
"model name is \U674e\U6d9b,model agestr is 26,model age is 24"
第三种为
"model name is \U674e\U6d9b2,model agestr is 24,model age is 26",
"model name is \U674e\U6d9b1,model agestr is 25,model age is 25",
"model name is \U674e\U6d9b,model agestr is 26,model age is 24"

OK,妈妈再也不用担心后台大佬乱给我传数据了。

---来自涛胖子的工作笔记

你可能感兴趣的:(一个装了model的数组通过model 的属性排序)