1.一般数组排序
//对数组进行排序 NSArray * array = 一般数组 NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { if (条件) { return [obj2 compare:obj1]; //降序 } else{ return [obj1 compare:obj2]; //升序 } }];
2.对象数组按照属性排序
(1)
如果是对象需要按照xxx属性来排序,就生成下面的descriptor // 创建排序条件 NSSortDescriptor *descriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"xxx" ascending:YES]; 如果需要多个排序,比如先按xxx排序,再按yyy排序。那就创建两个descriptor NSSortDescriptor *descriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"yyy" ascending:YES]; //排序 objArray = [objArray sortedArrayUsingDescriptors:@[descriptor1,descriptor2]];
(2)
vc.m中 //属性为字符串时 NSArray *newobjArr = [objArr sortedArrayUsingSelector:@selector(MyCompare:)]; // 属性为数字时 // NSArray *newobjArr = [objArr sortedArrayUsingSelector:@selector(MyCompare2:)]; CustomOneModel.m中实现比较方法 #import "CustomOneModel.h" @implementation CustomOneModel //属性为字符串时 -(NSComparisonResult)MyCompare:(CustomOneModel *)obj { return [self.name compare:obj.name]; } // 属性为数字时 - (NSComparisonResult)MyCompare2:(CustomOneModel *)obj { if ( self.height > obj.height ) { return NSOrderedDescending; } else if (self.height < obj.height ) { return NSOrderedAscending; } else { return NSOrderedSame; } } //CustomOneModel.h中需要声明MyCompare ,否则会出现黄色警告 @end