题目:
定义一个学生类,需要有姓名,年龄,考试成绩三个成员属性,创建5个对象,属性可以任意值。(Objective-C)
1) 不使用@property,手动编写他们的访问器方法(getter和setter),注意内存管理(手动管理内存)
2) 增加一个便利构造器(快速构造器)
3) 使用NSLog输出学生对象时,输出信息格式为:My Name Is XXX Age Is XXX Score Is XXX
4) 对5个学生对象按照成绩—》年龄—》姓名优先级排序(成绩相同按照年龄排序,成绩年龄相同按照姓名排序(5个学生的属性值自己随便设定,姓名不考虑中文,按26个大小字母排序))
//接口文件
student.h
//
// student.h
// 测试题5
//
// Created by smartlei on 15/5/26.
// Copyright (c) 2015年 smartlei. All rights reserved.
//
#ifndef ___5_student_h
#define ___5_student_h
@interface Student : NSObject
{
NSString *_name;//姓名
int _age;//年龄
float _record;//考试成绩
}
-(NSString *)name;
-(int)age;
-(float)record;
//增加一个便利构造器(快速构造器)
-(Student *)initWithName:(NSString *)name andAge:(int)age andRecord:(float)record;
-(NSArray *) sort:(NSArray *)myarry;//
-(NSComparisonResult)compareWithName:(id)element;
@end
#endif
实现文件student.m
//
// student.m
// 测试题5
//
// Created by smartlei on 15/5/26.
// Copyright (c) 2015年 smartlei. All rights reserved.
//姓名,年龄,考试成绩
#import <Foundation/Foundation.h>
#include "student.h"
@implementation Student
//使用NSLog输出学生对象时,输出信息格式为:My Name Is XXX Age Is XXX Score Is XXX
-(NSString *)description//覆盖继承的description方法,使%@按照以下方式固定显示
{
return [NSString stringWithFormat:@"My Name Is %@ Age Is %d Score Is %.3f",_name,_age,_record];
}
-(Student *)initWithName:(NSString *)name andAge:(int)age andRecord:(float)record
{
if (self=[super init])//初始化分配空见结束
{
_name=name;
_age=age;
_record=record;
}
return self;
}
-(NSString *)name
{
return _name;
}
-(int)age
{
return _age;
}
-(float)record
{
return _record;
}
@end
#import <Foundation/Foundation.h>
#include "student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu1=[[Student alloc] initWithName:@"zhanghui" andAge:15 andRecord:59];
Student *stu2=[[Student alloc] initWithName:@"xiaolizi" andAge:44 andRecord:59];
Student *stu3=[[Student alloc] initWithName:@"smartlei" andAge:44 andRecord:59];
Student *stu4=[[Student alloc] initWithName:@"zhaoming" andAge:28 andRecord:69];
Student *stu5=[[Student alloc] initWithName:@"gaohuidf" andAge:45 andRecord:79];
//创建数组
NSArray *myarray=[[NSArray alloc] initWithObjects:stu1,stu2,stu3,stu4,stu5, nil];
//提取数组中对象个数
// NSUInteger count=[myarray count];
//NSLog(@"%ld",count);
//构建排序描述器
NSSortDescriptor *stuName=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];//升序
NSSortDescriptor *stuage=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];//升序
NSSortDescriptor *sturecord=[NSSortDescriptor sortDescriptorWithKey:@"record" ascending:YES];//升序
NSArray *descriptior=[NSArray arrayWithObjects:sturecord,stuage,stuName, nil];
NSArray *lastArray=[myarray sortedArrayUsingDescriptors:descriptior];
for(Student *stu in lastArray)
{
NSLog(@"%@",stu);
}
// NSLog(@"%@",stu1);
}
return 0;
}