Objective Cの配列ソートをする方法1(sortedArrayUsingSelector:)

1.compare:メソッド
void sortArray1(){
NSArray *array = [NSArray arrayWithObjects:@"abc",@"123″,@"234″,@"789″,@"aef", nil];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(compare:)];
NSLog(@"ソート後:%@",sortedArray);
}

2.カスタムのソートメソッド
#import “Person.h"
@implementation Person
//静的メソッドを実装してnameとageを持つPersonオブジェクトを取得
+(Person *)personWithAge:(int) age withName:(NSString *)name{
Person *person = [[Person alloc] init];
person.age = age;
person.name = name;
return person;
}

//カスタムのソートメソッド
-(NSComparisonResult)comparePerson:(Person *)person{
//ageによってソート
NSComparisonResult result = [[NSNumber numberWithInt:person.age] compare:[NSNumber numberWithInt:self.age]];
//データ変換
//年齢が同じ場合、nameによってソート
if (result == NSOrderedSame) {
result = [self.name compare:person.name];
1 }
return result;
}

@end 主なメソッド:
void sortArray2(){
Person *p1 = [Person personWithAge:32 withName:@"恵理子"];
Person *p2 = [Person personWithAge:12 withName:@"百合子"];
Person *p3 = [Person personWithAge:24 withName:@"景子"];
Person *p4 = [Person personWithAge:24 withName:@"黒木"];
Person *p5 = [Person personWithAge:20 withName:@"真紀子"];
NSArray *array = [NSArray arrayWithObjects:p1,p2,p3,p4,p5, nil];
NSArray *sortedArray = [array sortedArrayUsingSelector:@selector(comparePerson:)];
NSLog(@"ソート後:%@",sortedArray);
}

IOS

Posted by arkgame