//方法1,使用自帶的比較器
數組
//compare是數組自帶的比較方法
spa
NSArray *array=[NSArray arrayWithObjects:@"3",@"1",@"2", nil];
code
NSArray *array2= [array sortedArrayUsingSelector:@selector(compare:)];
orm
NSLog(@"%@",array2);
對象
結果是升序排列排序
//方式二:使用塊完成排
ip
NSArray *array = [NSArray arrayWithObjects:@"1bc",@"4b6",@"123",@"789",@"3ef", nil];
string
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
it
//這裏的代碼能夠參照上面compare:默認的排序方法,也能夠把自定義的方法寫在這裏,給對象排序
io
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;
}
方法四:高級排序