一、一般排序
// 排序
NSArray *arr = @[@"",@"",@"",@""];
NSArray *newarr = [arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",newarr);
二、高级排序(数组中存的是对象,按对象的属性进行排序)
#import <Foundation/Foundation.h> @interface Student : NSObject @property (assign ,nonatomic) int age; //提供一种比较方式
- (NSComparisonResult)compareStudentWithAge:(Student *)tempStudent; @end #import "Student.h" @implementation Student - (NSComparisonResult)compareStudentWithAge:(Student *)tempStudent
{
//方法1:
// NSNumber *num1 = [[NSNumber alloc] initWithInteger:self.age];
// NSNumber *num2 = [[NSNumber alloc] initWithInteger:tempStudent.age];
// return [num1 compare:num2];
//方法2:
if (self.age>tempStudent.age) {
return NSOrderedDescending;
}
else if (self.age<tempStudent.age)
return NSOrderedAscending;
else
return NSOrderedSame;
} -(NSString *)description
{
return [NSString stringWithFormat:@"age:%d",self.age];
} @end #import <Foundation/Foundation.h> #import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool { Student *stu1 = [[Student alloc] init];
stu1.age= ;
Student *stu2 = [[Student alloc] init];
stu2.age= ;
Student *stu3 = [[Student alloc] init];
stu3.age= ; NSArray *stuArr = @[stu1,stu2,stu3];
NSArray *newStuArr = [stuArr sortedArrayUsingSelector:@selector(compareStudentWithAge:)];
NSLog(@"%@",newStuArr);
}
return ;
}
三、超级排序(数组中对象多属性)
#import <Foundation/Foundation.h> @interface People : NSObject @property (assign,nonatomic) NSInteger age;
@property (assign, nonatomic) NSInteger score;
@property (copy,nonatomic) NSString *name; @end #import "People.h" @implementation People - (NSString *)description
{
return [NSString stringWithFormat:@"age:%ld score:%ld name:%@", self.age,self.score,self.name];
} #import <Foundation/Foundation.h>
#import "People.h" int main(int argc, const char * argv[]) {
@autoreleasepool { People *stu1 = [[People alloc] init];
stu1.age = ;
stu1.score = ;
stu1.name = @"bowen1"; People *stu2 = [[People alloc] init];
stu2.age = ;
stu2.score = ;
stu2.name = @"bowen2"; People *stu3 = [[People alloc] init];
stu3.age = ;
stu3.score = ;
stu3.name = @"bowen3"; People *stu4 = [[People alloc] init];
stu4.age = ;
stu4.score = ;
stu4.name = @"bowen4"; People *stu5 = [[People alloc] init];
stu5.age = ;
stu5.score = ;
stu5.name = @"bowen5"; NSArray *arr = @[stu1,stu2,stu3,stu4,stu5]; // 排序描述,数组按属性排序 NSSortDescriptor
NSSortDescriptor *ageSort = [[NSSortDescriptor alloc] initWithKey:@"age" ascending:YES];
NSSortDescriptor *scoreSort = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:YES];
NSSortDescriptor *nameScort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; //使用[排序描述]对数组进行排序
NSArray *newArr = [arr sortedArrayUsingDescriptors:@[ageSort,scoreSort,nameScort]]; NSLog(@"%@",newArr); }
return ;
} @end