iOS数组排序-根据模型的属性排序

1.如下model

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface CSRAttentionModel : NSObject

@property(nonatomic) NSInteger createTime;

@end

NS_ASSUME_NONNULL_END

2.数组

  NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
  
  CSRAttentionModel* attentionModel = [[CSRAttentionModel alloc] init];
  attentionModel.createTime = 10;
  [array addObject:attentionModel];
  
  CSRAttentionModel* attentionModel2 = [[CSRAttentionModel alloc] init];
  attentionModel2.createTime = 10;
  [array addObject:attentionModel2];
  
  CSRAttentionModel* attentionModel3 = [[CSRAttentionModel alloc] init];
  attentionModel3.createTime = 8;
  [array addObject:attentionModel3];
  
  CSRAttentionModel* attentionModel4 = [[CSRAttentionModel alloc] init];
  attentionModel4.createTime = 4;
  [array addObject:attentionModel4];
  
  CSRAttentionModel* attentionModel5 = [[CSRAttentionModel alloc] init];
  attentionModel5.createTime = 17;
  [array addObject:attentionModel5];

3.根据model的属性createTime降序排序数组

NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:NO];
NSArray* sortPackageResListArr = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSLog(@"%@",sortPackageResListArr);

5.排序前后对比


排序前.png

排序后.png

6.扩展:
若想升序排序,只需要将ascending:的值传YES即可。
若还有另一个属性state,想在此前排序的基础上,在增加一条规则,如:优先按createTime降序,其次按state升序排序,则可如下:

NSSortDescriptor* sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:NO];
NSSortDescriptor* sortDescriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"state" ascending:YES];
NSArray* sortPackageResListArr = [array sortedArrayUsingDescriptors:@[sortDescriptor1,sortDescriptor2]];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 排序算法说明 (1)排序的定义:对一序列对象根据某个关键字进行排序; 输入:n个数:a1,a2,a3,…,an输出...
    BULL_DEBUG阅读 823评论 0 3
  • 1 初级排序算法 排序算法关注的主要是重新排列数组元素,其中每个元素都有一个主键。排序算法是将所有元素主键按某种方...
    深度沉迷学习阅读 1,501评论 0 1
  • Ba la la la ~ 读者朋友们,你们好啊,又到了冷锋时间,话不多说,发车! 1.冒泡排序(Bub...
    王饱饱阅读 1,837评论 0 7
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,173评论 1 32
  • 云主机购买后,先是升级了一波系统自带的 openssl 版本升级方法详见CentOS 服务器捣鼓「OpenSSL ...
    iSakura阅读 1,017评论 3 1