10、 定义一个学生类,需要有姓名,年龄,考试成绩三个成员属性,创建5个对象,属性可以任意值。(Objective-C)
1) 不使用@property,手动编写他们的访问器方法(getter和setter),注意内存管理(手动管理内存)
2) 增加一个便利构造器(快速构造器)
3) 使用NSLog输出学生对象时,输出信息格式为:My Name Is XXX Age Is XXX Score Is XXX
4) 对5个学生对象按照成绩—》年龄—》姓名优先级排序(成绩相同按照年龄排序,成绩年龄相同按照姓名排序(5个学生的属性值自己随便设定,姓名不考虑中文,按26个大小字母排序))
main.m文件
// 快速创建学生1
Student *s1 = [Student student];
s1.name = @"jack";
s1.age = 20;
s1.testScores = 86;
// 快速创建学生2
Student *s2 = [Student student];
s2.name = @"rose";
s2.age = 20;
s2.testScores = 86;
// 快速创建学生3
Student *s3 = [Student student];
s3.name = @"jim";
s3.age = 23;
s3.testScores = 95;
// 快速创建学生4
Student *s4 = [Student student];
s4.name = @"lilei";
s4.age = 21;
s4.testScores = 70;
// 快速创建学生5
Student *s5 = [Student student];
s5.name = @"lihua";
s5.age = 25;
s5.testScores = 86;
// 建立学生数组,储存学生信息
NSMutableArray *studentArray = [NSMutableArray arrayWithObjects:s1, s2, s3, s4, s5, nil ];
// 创建排序描述器
// 1.先按分数排序
NSSortDescriptor *scoresDesc= [NSSortDescriptor sortDescriptorWithKey:@"testScores" ascending:YES];
// 2.再按年龄排序
NSSortDescriptor *ageDesc= [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES];
// 3.再按姓名排序
NSSortDescriptor *nameDesc= [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
// 按顺序添加排序描述器
NSArray *descs = [NSArray arrayWithObjects:scoresDesc, ageDesc, nameDesc, nil];
NSArray *array = [studentArray sortedArrayUsingDescriptors:descs];
NSLog(@"%@",array);
[s1 release];
[s2 release];
[s3 release];
[s4 release];
[s5 release];
.h文件
@interface Student : NSObject
{
NSString *_name; // 姓名
int _age; // 年龄
int _testScores; // 考试成绩
}
// 姓名的setter和getter声明
- (void)setName:(NSString *)name;
- (NSString *)name;
// 年龄的setter和getter声明
- (void)setAge:(int)age;
- (int)age;
// 成绩的setter和getter声明
- (void)setTestScores:(int)testScores;
- (int)testScores;
+ (id)student; // 快速构造方法声明
.h文件
// 姓名的setter和getter的实现
- (void)setName:(NSString *)name
{
if (_name != name)
{
[_name release];
_name = [name retain];
}
}
- (NSString *)name
{
return _name;
}
// 年龄的setter和getter的实现
- (void)setAge:(int)age
{
_age = age;
}
- (int)age
{
return _age;
}
// 成绩的setter和getter的实现
- (void)setTestScores:(int)testScores
{
_testScores = testScores;
}
- (int)testScores
{
return _testScores;
}
// 快速构造方法实现
+ (id)student
{
return [[[self alloc] init] autorelease];
}
- (NSString *)description
{
return [NSString stringWithFormat:@"My Name Is %@ Age Is %d Score Is %d", _name, _age, _testScores];
}
- (void)dealloc
{
[_name release];
[super dealloc];
}
|
|