#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (retain,nonatomic) NSString *name;
@property (assign,nonatomic)int age;
- (void) setAge: (int)newAge;
- (NSComparisonResult)myCompare: (id)anObject;
+ (Student *)studentWithName:(NSString *)n andAge:(int)a;
@end
#import "Student.h"
@implementation Student
@synthesize name,age;
+ (Student *)studentWithName:(NSString *)n andAge:(int)a{
Student *student = [[Student alloc] init];
student.name=n;
student.age=a;
return [student autorelease];
}
//重写父类description
- (NSString *)description{
return [NSString stringWithFormat:@"我叫%@,我今年%d岁了!",self.name,self.age];
}
- (NSComparisonResult)myCompare: (id)anObject{
//以名字来排序
NSComparisonResult result = [[self name]compare:[anObject name]];
return result;
}
- (void) setAge: (int)newAge{
if (newAge<0) {
// NSLog(@"岁数不合适");
age=18;
}else{
age=newAge;
}
}
@end
#import <Foundation/Foundation.h>
#import "Student.h"
void sort(id arr){
for (id obj in arr) {
NSLog(@"%@",obj);
}
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
Student *stu1 = [Student studentWithName:@"大胖" andAge:-3];
Student *stu2 = [Student studentWithName:@"二胖" andAge:24];
Student *stu3 = [Student studentWithName:@"小胖" andAge:23];
NSMutableArray *mArr = [NSMutableArray arrayWithObjects:stu1,stu2,stu3, nil];
sort(mArr);
//使用sortUsingDescriptors排序
//定义一个排序描述符对象
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:1];
//定义一个数组,arr1用来盛放排序条件
NSArray *arr1 = [NSArray arrayWithObjects:sd1, nil];
//进行排序
[mArr sortUsingDescriptors:arr1];
NSLog(@"-------排序后------");
sort(mArr);
/*----------------------------------------------------*/
//对于不可变数组的排序
NSArray *arr2 = [NSArray arrayWithObjects:stu1,stu2,stu3, nil];
//arr2排序前
NSLog(@"+++不可变数组排序前的数据+++");
sort(arr2);
//进行排序
NSArray *arr3 = [arr2 sortedArrayUsingDescriptors:arr1];
NSLog(@"+++不可变数组排序后的数据+++");
sort(arr3);
/*----------------------------------------------------*/
//使用sortUsingSelector方法
NSLog(@"=========================");
NSMutableArray *mArr3 = [NSMutableArray arrayWithObjects:stu1,stu2,stu3, nil];
[mArr3 sortUsingSelector:@selector(myCompare:)];
sort(mArr3);
//使用selector进行字符串排序
NSMutableArray *mArr4 = [[NSMutableArray alloc] initWithObjects:@"Arc",@"cfo",@"hBl",@"Pon", nil];
[mArr4 sortUsingSelector:@selector(compare:)];
NSLog(@"对字符排序后的结果为");
sort(mArr4);
}
return 0;
}