iOS 数组模型排序

 

 

@interface BookCityBookModel : NSObject

@property (nonatomic, copy) NSString bookId;


@property (nonatomic, copy) NSString *bookName;

@end

1、根据单个属性升序排序

self.dataArray = [NewMembersModel mj_objectArrayWithKeyValuesArray:response[@"data"]];
// 排序key, 某个对象的属性名称,是否升序, YES-升序, NO-降序
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"bookName" ascending:YES];
// 排序结果
self.tempArr = [self.dataArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

2、根据多个属性一个升序一个降序排序 

self.dataArray = [NewMembersModel mj_objectArrayWithKeyValuesArray:response[@"data"]];
// 排序key, 某个对象的属性名称,是否升序, YES-升序, NO-降序
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"bookName" ascending:YES];
NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"bookId" ascending:NO];
// 排序结果
self.tempArr = [self.dataArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor, sortDescriptor1, nil]];

 

sortedArrayUsingDescriptors有个需要注意的,当然sortUsingDescriptors可变数组一样存在,当你选择对应key值进行排序时,一般是数值排序,那key所对应的value就不能是NSString类型。key所对应的value是NSString类型就得用以下方法转化下就可以了

[self.bookArray sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2){
		BookCityBookModel *mode1 = obj1;
		BookCityBookModel *mode2 = obj2;
		if ([mode1.bookId integerValue] < [mode2.bookId integerValue]){
			return NSOrderedAscending;

		}else{
				return NSOrderedDescending;
			}
	}];
	NSLog(@"%@",self.bookArray);
	for (int i = 0; i

 

 

 

 

iOS 数组模型排序_第1张图片

 

你可能感兴趣的:(iOS)