#import <Foundation/Foundation.h>
@interface Student : NSObject
{
@public
NSString*_name;
int _age;
int _score;
}
-(void)setName:(NSString*)name;
-(NSString*)name;
-(void)setAge:(int)age;
-(int)age;
-(void)setScore:(int)score;
-(int)score;
-(void)printf;
-(instancetype)initWithName:(NSString*)name andAge:(int)age andScore:(int)score;
@end
@implementation Student
-(void)dealloc{
//子类先释放
[_name release];
//释放父类
[super dealloc];
}
-(void)setName:(NSString*)name{
if (_name!=name) {//release旧值,retain新值
[_name release];
_name=[name retain];
}
}
-(NSString*)name{
return _name;
}
-(void)setAge:(int)age{
_age=age;
}
-(int)age{
return _age;
}
-(void)setScore:(int)score{
_score=score;
}
-(int)score{
return _score;
}
-(void)printf{
NSLog(@"学生的姓名是:%@,年龄是:%d,分数是:%d",_name,_age,_score);
}
-(instancetype)initWithName:(NSString*)name andAge:(int)age andScore:(int)score{
if (self=[super init]) {
_name=name;
_age=age;
_score=score;
}
return self;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建五个学生
Student*s1=[[Student alloc]initWithName:@"aa" andAge:20 andScore:80];
Student*s2=[[Student alloc]initWithName:@"bb" andAge:21 andScore:70];
Student*s3=[[Student alloc]initWithName:@"cc" andAge:22 andScore:70];
Student*s4=[[Student alloc]initWithName:@"dd" andAge:19 andScore:60];
Student*s5=[[Student alloc]initWithName:@"ee" andAge:20 andScore:90];
//把五个对象加入到数组中去
NSArray *stuArray=@[s1,s2,s3,s4,s5];
//设定排序规则
//按姓名排序
NSSortDescriptor *d1=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
//按年龄排序
NSSortDescriptor *d2=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
//按分数排序
NSSortDescriptor *d3=[NSSortDescriptor sortDescriptorWithKey:@"score" ascending:NO];
//定义新的数组来接受排序后的结果
NSArray *array=[stuArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:d3,d2,d1, nil]];
//循环遍历
[array enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[obj printf];
}];
}
return 0;
} |