不可变的
NSArray *arr= @[@"1",@"2",@"3"];
arr =[arr sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"%@",arr);
arr= [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj2 compare:obj1];
}];
NSLog(@"%@",arr);
可变的
NSMutableArray *a = [NSMutableArray arrayWithObjects:@"a",@"b",@"c", nil];
[a sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// return [obj1 compare:obj2];
return [obj2 compare:obj1];
}];
NSLog(@"%@",a);
[a sortUsingSelector:@selector(compare:)];
NSLog(@"%@",a);
// 对象的数组排序
Person *p1 =[[Person alloc] init];
p1.name=@"001";
Person *p2 =[[Person alloc] init];
p2.name=@"002";
Person *p3 =[[Person alloc] init];
p3.name=@"003";
Person *p4 =[[Person alloc] init];
p4.name=@"004";
// NSArray *arr =[NSArray arrayWithObjects:s1,s2,s3, nil];
NSArray *arr =[NSArray arrayWithObjects:p1,p2,p3, nil];
arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//compare只能比字符串
Person *p1= obj1;
Person *p2= obj2;
return [p1.name compare:p2.name];
}];
for (Person *p in arr) {
NSLog(@"%@",p.name);
}
原文:http://www.cnblogs.com/wxios/p/4183596.html