今天我们学习两个方法, 一个是对字符串进行排序的方法,一个是对常量数进行排序的方法.
创建一个Person类,并且在Person.h文件中,设置实例 初始化 以及setter getter方法 另外把排序的方法声明在Person.h文件中.
#import <Foundation/Foundation.h>
@interface Person : NSObject
//1.设置三个实例 name sex age
{
NSString *_name;
NSString *_sex;
NSInteger _age;
}
//2.指定初始化
- (id)initWithName:(NSString *)name
sex:(NSString *)sex
age:(NSInteger)age;
//3.setter getter方法
- (void)setName:(NSString *)name;
- (NSString *)name;
- (void)setSex:(NSString *)sex;
- (NSString *)sex;
- (void)setAge:(NSInteger)age;
- (NSInteger)age;
//4.声明一个按姓名排序的方法
- (NSComparisonResult)compareByNameWithOtherPerson:(Person *)anotherPerson;
//5.声明一个按年龄排序的方法
- (NSComparisonResult)compareByAgeWithOtherPerson:(Person*)anotherPerson;
//6.声明一个description
- (NSString *)description;
@end
//调转到Person.m中进行方法的实现
在Person.h文件中声明之后,将2.3.4.5.6复制下来,到Person.m文件进行实现.
#import "Person.h"
@implementation Person
//2.指定初始化
- (id)initWithName:(NSString *)name
sex:(NSString *)sex
age:(NSInteger)age
{
self = [super init];
if (self) {
_name = name;
_sex = sex;
_age = age;
}
return self;
}
//3.setter getter方法
- (void)setName:(NSString *)name
{
_name = name;
}
- (NSString *)name
{
return _name;
}
- (void)setSex:(NSString *)sex
{
_sex = sex;
}
- (NSString *)sex
{
return _sex;
}
- (void)setAge:(NSInteger)age
{
_age = age;
}
- (NSInteger)age
{
return _age;
}
//4.声明一个按姓名排序的方法
- (NSComparisonResult)compareByNameWithOtherPerson:(Person *)anotherPerson
{
if ([self.name compare:anotherPerson.name] > 0) {
return NSOrderedDescending;
}else if ([self.name compare:anotherPerson.name] < 0)
{
return NSOrderedAscending;
}
return NSOrderedSame;
}
//5.声明一个按年龄排序的方法
- (NSComparisonResult)compareByAgeWithOtherPerson:(Person*)anotherPerson
{
if (self.age > anotherPerson.age) {
return NSOrderedDescending;
}else if (self.age < anotherPerson.age)
{
return NSOrderedAscending;
}
return NSOrderedSame;
}
//6.声明一个description
- (NSString *)description
{
return [NSString stringWithFormat:@"name:%@ , sex: %@, age:%ld",_name,_sex,_age];
}
@end
方法声明及实现之后,我们就要跳转到main函数中进行调用方法
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//7.创建4个对象
Person *obj1 = [[Person alloc] initWithName:@"Jack" sex:@"male" age:22];
Person *obj2 = [[Person alloc] initWithName:@"Henry" sex:@"male" age:28];
Person *obj3 = [[Person alloc] initWithName:@"Elyse" sex:@"female" age:26];
Person *obj4 = [[Person alloc] initWithName:@"Lisa" sex:@"female" age:24];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:obj1,obj2,obj3,obj4, nil];
//8. 数组按照名字排序
[array sortUsingSelector:@selector(compareByNameWithOtherPerson:)];
//调用compareByName这个方法,在运行的时候,会首先跳转到Person.h中,看看有没有这个方法,找到后,就会跳转到Person.m中,运行方法,然后在跳转到main函数中,把结果显示出来.
NSLog(@"%@",array);
//9. 数组按照年龄排序
[array sortUsingSelector:@selector(compareByAgeWithOtherPerson:)];
//调用compareByAge这个方法,在运行的时候,会首先跳转到Person.h中,看看有没有这个方法,找到后,就会跳转到Person.m中,运行方法,然后在跳转到main函数中,把结果显示出来.
NSLog(@"%@",array);
}
return 0;
}
这次主要是把字符串排序和常量数的排序掌握, 以后应该还会经常用到,所以把方法记住!