OC數(shù)組排序

?1.使用NSSortDescriptor對(duì)象進(jìn)行數(shù)組排序

//創(chuàng)建一個(gè)數(shù)組

NSArray *array = @[@"one", @"two", @"three", @"four", @"six"];

//創(chuàng)建一個(gè)排序條件,也就是一個(gè)NSSortDescriptor對(duì)象

//其中第一個(gè)參數(shù)為數(shù)組中對(duì)象要按照什么屬性來排序(比如自身、姓名,年齡等)

//第二個(gè)參數(shù)為指定排序方式是升序還是降序

//ascending? 排序的意思,默認(rèn)為YES 升序

NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES];

NSArray *newArray = [array sortedArrayUsingDescriptors:@[des]];

NSLog(@"%@",newArray);

2.使用sortedArrayUsingDescriptors:方法實(shí)現(xiàn)把多個(gè)排序條件放到數(shù)組中,實(shí)現(xiàn)多條件排序,按數(shù)組先后順序,先加入的優(yōu)先級(jí)高

//創(chuàng)建一個(gè)Person類

Person *p1 = [[Person alloc] initWithName:@"zhonger" age:@"19"];

Person *p2 = [[Person alloc] initWithName:@"zhubada" age:@"11"];

Person *p3 = [[Person alloc] initWithName:@"zhubada" age:@"1"];

Person *p4 = [[Person alloc] initWithName:@"zhubada" age:@"33"];

Person *p5 = [[Person alloc] initWithName:@"hehehe" age:@"38"];

NSArray *person = @[p1, p2, p3, p4, p5];

NSSortDescriptor *des1 = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];

NSSortDescriptor *des2 = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO];

NSArray *newArray1 = [person sortedArrayUsingDescriptors:@[des1,des2]];

NSLog(@"%@",newArray1);

3.使用sortedArrayUsingComparator進(jìn)行數(shù)組排序

Comparator的返回結(jié)構(gòu)枚舉類型含義:

NSOrderedAscending//升序

The left operand is smaller than the right operand.

NSOrderedSame

The two operands are equal.

NSOrderedDescending//降序

The left operand is greater than the right operand.

直接使用代碼塊對(duì)字典里具體屬性進(jìn)行排序

NSString *arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {

NSString *age1 = [obj1 objectForKey:@"age"];

NSString *age2 = [obj2 objectForKey:@"age"];

//轉(zhuǎn)換成NSNumber便于直接使用compare:方法直接排序

NSNumber *num1 = [NSNumber numberWithInteger:age1];

NSNumber *num2 = [NSNumber numberWithInteger:age2];

//升序

NSComparisonResult result = [num1 compare:num2];

return result;

}];

NSLog(@"%@",arr);

//其中compare:內(nèi)部實(shí)現(xiàn)類似于下(也可自定義對(duì)象的比較方法)

NSComparator cmp = ^(id obj1, id obj2) {

if ([obj1 integerValue] < [obj2 integerValue]) {

? ? ? return (NSComparisonResult)NSOrderedAscending;? ?? ? ?

}else if ([obj1 integerValue] > [obj2 integerValue]) {

? ? ? return (NSComparisonResult)NSOrderedDescending;?

}else {

? ? ? return (NSComparisonResult)NSOrderedSame;

};

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容