OC-排序-自定义类型对象的排序
.main.m 代码
/********** 自定义类型对象的排序 *****************/
Person *per1 = [[Person alloc] initWithName:@"Long" age:22];
Person *per2 = [[Person alloc] initWithName:@"Bian" age:18];
Person *per3 = [[Person alloc] initWithName:@"YI" age:20];
NSMutableArray *perArr = [NSMutableArray arrayWithObjects:per1, per2, per3, nil];
[perArr sortUsingSelector:@selector(compareWithName:)];
//[perArr sortedArrayUsingSelector:@selector(compareWithAge:)];
for (Person *per in perArr) {
NSLog(@"%@ %ld", per.name, per.age);
}
Person.h 代码
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
(instancetype)initWithName:(NSString *)name
age:(NSInteger)age;
- (NSComparisonResult)compareWithName:(Person *)per;
- (NSComparisonResult)compareWithAge:(Person *)per;
Person.m 代码
- (instancetype)initWithName:(NSString *)name
age:(NSInteger)age
{
self = [super init];
if (self) {
self.name = name;
self.age = age;
}
return self;
}
- (NSComparisonResult)compareWithName:(Person *)per
{
return [self.name compare:per.name] ;
}
(NSComparisonResult)compareWithAge:(Person *)per
{
if (self.age > per.age) {return NSOrderedDescending;
} else if (self.age < per.age) {
return NSOrderedAscending;
} else {
return NSOrderedSame;
}
}