标签:nsarray ios开发 objective-c 数组排序 block
Person类中
@property(nonatomic,strong) NSString * name ;
@property(nonatomic ,strong)NSString *year;
@property(nonatomic,assign) int age;
-(id)initWithName:(NSString *)name andYear:(NSString *)year andAge:(int)age;
- (NSString *)description
{
return [NSString stringWithFormat:@"name=%@,year=%@,age=%d", _name,_year,_age];
}
//初始化
-(id)initWithName:(NSString *)name andYear:(NSString *)year andAge:(int)age
{
if (self =[super init])
{
_name=name;
_year=year;
_age=age;
}
return self;
}
//1.数组按照存入数据的顺序存储的。
NSArray *array=@[@"b",@"d",@"1",@"a",@"z",@"2"];
NSLog(@"排序前 array %@",array);
array= [array sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"排序后 array %@",array);
//2.使用block方式排序。
NSArray *array1=@[@"z",@"4",@"3",@"x"];
NSLog(@"array1 排序前%@",array1);
array1 =[array1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// NSComparisonResult rersult=[obj1 compare:obj2];
// return rersult;
return [obj1 compare:obj2];
}];
NSLog(@"array1 排序后 %@",array1);
//3.自定对象的排序,根据属性排序
Person *p=[[Person alloc]initWithName:@"jack "andYear:@"1990" andAge:20];
Person *p1=[[Person alloc]initWithName:@"tom" andYear:@"2000"andAge:21];
Person *p2=[[Person alloc]initWithName:@"hoo "andYear:@"1908" andAge:18];
Person *p3=[[Person alloc]initWithName:@"hoo1 "andYear:@"1907" andAge:18];
NSArray *array2=@[p,p1,p2,p3];
NSLog(@"排序前 array2 %@",array2);
NSSortDescriptor *d1=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
NSSortDescriptor *d2=[NSSortDescriptor sortDescriptorWithKey:@"year" ascending:YES];
NSArray *descripts=@[d1,d2];
array2 =[array2 sortedArrayUsingDescriptors:descripts];
NSLog(@"排序后 array2%@",array2);
//4.自定义对象的block方法排序
NSArray *array4=@[p,p1,p2,p3];
NSLog(@"array4 排序前%@",array4);
array4=[array4 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
Person *p1=obj1;
Person *p2=obj2;
return [p1.year compare:p2.year];
}];
NSLog(@"array4 排序后 %@",array4);
标签:nsarray ios开发 objective-c 数组排序 block
原文地址:http://blog.csdn.net/u010804473/article/details/45245073