ios数组里的model排序(高级排序)

xiaoxiao2021-02-27  171

- (NSMutableArray *)datas { if (!_datas) { _datas = [NSMutableArray array]; Person *p1 = [[Person alloc] initWithName:@"jack" age:20 score:97]; Person *p2 = [[Person alloc] initWithName:@"anne" age:8 score:33]; Person *p3 = [[Person alloc] initWithName:@"zhng" age:54 score:11]; Person *p4 = [[Person alloc] initWithName:@"tuoma" age:76 score:54]; Person *p5 = [[Person alloc] initWithName:@"gril" age:95 score:12]; Person *p6 = [[Person alloc] initWithName:@"boy" age:21 score:76]; Person *p7 = [[Person alloc] initWithName:@"big" age:53 score:98]; Person *p8 = [[Person alloc] initWithName:@"hack" age:33 score:66]; Person *p9 = [[Person alloc] initWithName:@"zoom" age:33 score:21]; Person *p10 = [[Person alloc] initWithName:@"right" age:69 score:88]; [_datas addObject:p1]; [_datas addObject:p2]; [_datas addObject:p3]; [_datas addObject:p4]; [_datas addObject:p5]; [_datas addObject:p6]; [_datas addObject:p7]; [_datas addObject:p8]; [_datas addObject:p9]; [_datas addObject:p10]; } return _datas;

}

接下来我们需要进行排序:

 规则如下:

  1.首先按照年龄排序

  2.如果年龄相同按照分数排序

那么我们需要创建排序描述者,一个描述着只能对一个属性进行描述 如果需要描述多个 我们需要创建多个描述者

我们这里的需求就需要创建两个描述者  一个是对年龄描述 一个是对分数描述 代码如下:

NSSortDescriptor *ageSD = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];//ascending:YES 代表升序 如果为NO 代表降序 NSSortDescriptor *scoreSD=[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES];

创建好这两个描述者之后 我们就可以调用数组的 sortedArrayUsingDescriptors 方法来实现排序

sortedArrayUsingDescriptors方法接收一个数组的参数 里面放描述者 然后他会返回一个排序好的数组 所以我们这样做:

self.datas = [[self.datas sortedArrayUsingDescriptors:@[ageSD,scoreSD]] mutableCopy];

我们点击导航栏左边的排序按钮的时候 会执行以下操作:

- (IBAction)sortAge:(id)sender { NSSortDescriptor *ageSD = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; NSSortDescriptor *scoreSD=[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:YES]; self.datas = [[self.datas sortedArrayUsingDescriptors:@[ageSD,scoreSD]] mutableCopy]; //[self.datas sortUsingDescriptors:@[ageSD,scoreSD]] 可能也可以 [self.tableView reloadData]; } http://www.cnblogs.com/syios/p/5918868.html
转载请注明原文地址: https://www.6miu.com/read-16102.html

最新回复(0)