iOS array model sorting

 

 

@interface BookCityBookModel : NSObject

@property (nonatomic, copy) NSString bookId;


@property (nonatomic, copy) NSString *bookName;

@end

1. Sort in ascending order according to a single attribute

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. Sort in ascending order and descending order according to multiple attributes 

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]];

 

There is one thing to note about sortedArrayUsingDescriptors. Of course, the variable array of sortUsingDescriptors also exists. When you select the corresponding key value for sorting, it is usually a numeric sort, and the value corresponding to the key cannot be of type NSString. The value corresponding to the key is of NSString type, so you have to use the following method to transform it.

[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<self.bookArray.count; i++) {
		BookCityBookModel *mode = self.bookArray[i];
		NSLog(@"%@",mode.bookId);
	}

 

 

 

 

 

Guess you like

Origin blog.csdn.net/zjpjay/article/details/88406748