-----------------------------------------------------------------------------------------------------------------------------------------------------------
//
// Student.h
// OCdemo-05-shuzupaixu
//
// Created by lanou3g on 15/10/13.
// Copyright (c) 2015年 Object. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
NSString *_name; //姓名
NSInteger _age; //年龄
}
-(void)setName:(NSString *)name;
-(void)setAge:(NSInteger)age;
-(NSString *)getName;
-(NSInteger)getAge;
//自定义初始化方法
-(instancetype)initWithName:(NSString *)name
age:(NSInteger)age;
//便利构造器
+(instancetype)studentWithName:(NSString *)name
age:(NSInteger)age;
//按照姓名排序
-(NSComparisonResult)compareStudentByName:(Student *)otherStudent;
//按照年龄排序
-(NSComparisonResult)compareStudentByAge:(Student *)otherStudent;
@end
-----------------------------------------------------------------------------------------------------------------------------------------------------------
//
// Student.m
// OCdemo-05-shuzupaixu
//
// Created by lanou3g on 15/10/13.
// Copyright (c) 2015年 Object. All rights reserved.
//
#import "Student.h"
@implementation Student
-(void)setName:(NSString *)name{
_name = name;
}
-(void)setAge:(NSInteger)age{
_age = age;
}
-(NSString *)getName{
return _name;
}
-(NSInteger)getAge{
return _age;
}
//自定义初始化方法
-(instancetype)initWithName:(NSString *)name
age:(NSInteger)age{
self = [super init];
if (self) {
_name = name;
_age = age;
}
return self;
}
//便利构造器
+(instancetype)studentWithName:(NSString *)name
age:(NSInteger)age{
Student *student = [[Student alloc] initWithName:name age:age];
return student;
}
//按照姓名排序
-(NSComparisonResult)compareStudentByName:(Student *)otherStudent{
if ([[self getName]compare:[otherStudent getName]] == NSOrderedAscending) {
return NSOrderedAscending; //升序排列
}else if ([[self getName] compare:[otherStudent getName]] == NSOrderedDescending){
return NSOrderedDescending; //降序
} else {
return NSOrderedSame; // 相等
}
return [[self getName] compare:[otherStudent getName]];
}
//按照年龄排序
-(NSComparisonResult)compareStudentByAge:(Student *)otherStudent{
if ([self getAge] > [otherStudent getAge]) {
return NSOrderedDescending; //降序
} else if( [self getAge] < [otherStudent getAge] ){
return NSOrderedAscending; //升序
}else{
return NSOrderedSame;
}
}
@end