NSArray几种排序方式
2017-01-22 本文已影响97人
楼上那只猫
1.数组中存放字符串
NSArray * arr = @[@"bsdf", @"afe", @"c2", @"frtagrga", @"zss", @"wf", @"e"];
NSArray * sortArr = [arr sortedArrayUsingSelector:@selector(compare:)]; //默认升序
如果要降序,有下面2种方法
1
NSSortDescriptor * des = [NSSortDescriptorsortDescriptorWithKey:nil ascending:NO]; //YES为升序,NO为降序
NSArray * harr = [arr sortedArrayUsingDescriptors:@[des]];
2
NSArray * sortArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj2 compare:obj1 options:NSCaseInsensitiveSearch]; //obj1在前为升序,obj2在前为降序
}];
2.如果数组中存储的是数字类型的字符串或者 NSNumber
NSArray * arr = @[@"2", @"1", @"34", @"54", @"5", @"66", @"90", @"12"];
NSArray * sortArr = [arr sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
//改变返回值可以改变排序方式
if ([obj1 integerValue] > [obj2 integerValue]) {
return NSOrderedDescending;
} else if ([obj1 integerValue] < [obj2 integerValue]) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}];
3.数组中存储的是对象类型,根据对象中的某个属性进行排序
Person * p1 = [[Person alloc] init];
p1.age = 22;
Person * p2 = [[Person alloc] init];
p2.age = 13;
Person * p3 = [[Person alloc] init];
p3.age = 6;
Person * p4 = [[Person alloc] init];
p4.age = 44;
NSArray * arr = @[p1, p2, p3, p4];
NSSortDescriptor * des = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:NO]; //age是Person的一个属性,即按照age进行排序
NSLog(@"%@", [arr sortedArrayUsingDescriptors:@[des]]);
4.自定义方法排序(这个方法定义在要排序的对象中,如:Person类中)
- (NSComparisonResult)comparePerson:(Person *)p {
if (self.age < p.age) { //如果自身对象小于参数对象,返回升序,否则降序
return NSOrderedAscending;
} else {
return NSOrderedDescending;
}
}