您的位置:首页 > 移动开发 > IOS开发

iOS数组排序

2016-07-02 08:55 387 查看
一、利用NSSortDescriptor对象数组排序

NSSortDescriptor可以根据数组中对象的属性来排序,为排序数组的要排序的属性创建NSSortDescriptor对象,将所有这些对象放入一个数组中,该数组将会在后面用作参数。使用NSArray类的sortedArrayUsingDescripors:方法并将NSSortDescriptor对象数组作为参数传递过去,会返回一个排好序的数组。

创建Person类用于排序

Person.h

@interface Person : NSObject
@property (nonatomic, copy) NSString *firstName;
@property (nonatomic, copy) NSString *lastName;
@property (nonatomic, assign) NSInteger age;
-(instancetype)initWithFirstName:(NSString *)fName lastName:(NSString *)lName age:(NSInteger) age;


Person.m

@implementation Person
-(instancetype)initWithFirstName:(NSString *)fName lastName:(NSString *)lName age:(NSInteger)age    {
self = [super init];
if (self) {
self.firstName = fName;
self.lastName = lName;
self.age = age;
}
return self;
}


排序

Person *p1 = [[Person alloc] initWithFirstName:@"Wenxuan" lastName:@"Huo" age:21];
Person *p2 = [[Person alloc] initWithFirstName:@"MaHa" lastName:@"B" age:30];
Person *p3 = [[Person alloc] initWithFirstName:@"MeKe" lastName:@"C" age:30];
Person *p4 = [[Person alloc] initWithFirstName:@"MaLian" lastName:@"A" age:30];
Person *p5 = [[Person alloc] initWithFirstName:@"HoHo" lastName:@"A" age:40];
Person *p6 = [[Person alloc] initWithFirstName:@"Guo" lastName:@"Zhong" age:5000];

// 包含所有Person的数组
NSArray *peopleArray = @[p1, p2, p3, p4, p5, p6];

// 为每个要排序的属性创建NSSortDescriptor对象
NSSortDescriptor * sdFirstName = [NSSortDescriptor sortDescriptorWithKey:@"firstName"   ascending:YES];
NSSortDescriptor * sdLastName = [NSSortDescriptor sortDescriptorWithKey:@"lastName"     ascending:YES];
NSSortDescriptor * sdAge = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];

// 设置排序优先级,并组成数组。这里优先级最高为age,之后是lastName,最后是firstName
NSArray * sortedArray = [peopleArray sortedArrayUsingDescriptors:@[sdAge, sdLastName, sdFirstName]];
// 为数组中每个元素执行方法,输出状态
[sortedArray makeObjectsPerformSelector:@selector(printState)];


makeObjectsPerformSelector
1

二、利用sortedArrayUsingComparator

调用NSComparator

//升序排列
NSComparator cmptr = ^(id obj1,id obj2){

if([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}

if([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}

return (NSComparisonResult)NSOrderedSame;
};

NSArray *sortArray = [[NSArray alloc] initWithObjects:@"1",@"3",@"4",@"7",@"8",@"2",@"6",@"5",@"13",@"15",@"12",@"20",@"28",@"",nil];
sortArray = [sortArray sortedArrayUsingComparator:cmptr];


makeObjectsPerformSelector:@select(aMethod) 让数组中的每个元素都调用aMethod
makeObjectsPerformSelector:@select(aMethod)withObject:oneObject 让数组中的每个元素 都调用 aMethod 并把 withObject 后边的 oneObject 对象做为参数传给方法aMethod
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios