NSArray 数组排序
-
//方法1,使用自带的比较器
-
//compare是数组自带的比较方法
-
NSArray *array=[NSArray arrayWithObjects:@"3",@"1",@"2", nil];
-
NSArray *array2= [array sortedArrayUsingSelector:@selector(compare:)];
-
NSLog(@"%@",array2);
结果是升序排列
-
//方式二:使用块完成排
-
NSArray *array = [NSArray arrayWithObjects:@"1bc",@"4b6",@"123",@"789",@"3ef", nil];
-
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
-
-
//这里的代码可以参照上面compare:默认的排序方法,也可以把自定义的方法写在这里,给对象排序
-
NSComparisonResult result = [obj1 compare:obj2];
-
return result;
-
}];
-
NSLog(@"排序后:%@",sortedArray);
方法3:自定义排序
-
#import <Foundation/Foundation.h>
-
-
@interface Person : NSObject
-
@property NSString* name;
-
@property int age;
-
-
-(id)initWithNameAndAge:(NSString*) aName and:(int) aAge;
-
-(NSComparisonResult)comparePersonByAge:(Person *)person;
-
-(NSComparisonResult)comparePersonByName:(Person *)person;
-
@end
-
#import "Person.h"
-
-
@implementation Person
-
@synthesize name,age;
-
-(id)initWithNameAndAge:(NSString*) aName and:(int) aAge{
-
if (self=[super init]) {
-
-
name=aName;
-
age=aAge;
-
-
}
-
return self;
-
}
-
-
//自定义排序方法
-
-(NSComparisonResult)comparePersonByAge:(Person *)person{
-
//默认按年龄排序
-
NSComparisonResult result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];//注意:基本数据类型要进行数据转换
-
//如果年龄一样,就按照名字排序
-
//if (result == NSOrderedSame) {
-
// result = [self.name compare:person.name];
-
//}
-
return result;
-
}
-
-
-(NSComparisonResult)comparePersonByName:(Person *)person{
-
//默认按年龄排序
-
NSComparisonResult result = [ person.name compare:self.name];//注意:基本数据类型要进行数据转换
-
//如果年龄一样,就按照名字排序
-
if (result == NSOrderedSame) {
-
result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];
-
}
-
return result;
-
}
-
-
-
- (NSString *)description
-
{
-
return [NSString stringWithFormat:@"%@ %d", name,age];
-
}
-
@end
-
#import <Foundation/Foundation.h>
-
#import "Person.h"
-
-
int main(int argc, const char * argv[]) {
-
@autoreleasepool {
-
Person *p1 = [[Person alloc]initWithNameAndAge:@" qweasadsasd" and:25];
-
Person *p2 = [[Person alloc]initWithNameAndAge:@"\t1234" and:28];
-
Person *p3 = [[Person alloc]initWithNameAndAge:@"123" and:2];
-
Person *p4 = [[Person alloc]initWithNameAndAge:@"zxc" and:89];
-
Person *p5 = [[Person alloc]initWithNameAndAge:@"123" and:8];
-
-
NSArray * persons = [NSArray arrayWithObjects:p1,p2,p3,p4,p5,nil];
-
NSArray *sortedArray = [persons sortedArrayUsingSelector:@selector(comparePersonByName:)];
-
NSLog(@"排序后:%@",sortedArray);
-
}
-
return 0;
-
}
方法四:高级排序