NSArray利用Cocoa框架进行汉字排序
NSArray利用Cocoa框架進行漢字排序
在NSString有一個函數localizedCompare:,它的功能是通過自身與給定字符串的比較,返回一個本地化的比較結果。也就是說這個函數是支持漢字比較的。
Student.h
@interface Student : NSObject
@property(nonatomic,copy)NSString *stuName;
@property(nonatomic,assign)CGFloat stuScore;
@property(nonatomic,copy)NSString *stuSex;
@property(nonatomic,assign)NSInteger stuAge;
-(id)initWithName:(NSString *)stuName
? ? ? andStuScore:(CGFloat) stuScore
? ? ? ? andStuSex:(NSString *) stuSex
? ? ? ? andStuAge:(NSInteger) stuAge;
+(id)StudentWithName:(NSString *)stuName
?? ? ? ? andStuScore:(CGFloat) stuScore
?? ? ? ? ? andStuSex:(NSString *) stuSex
?? ? ? ? ? andStuAge:(NSInteger) stuAge;
@end
Student.m
@implementation Student
-(id)initWithName:(NSString *)stuName
? ? ? andStuScore:(CGFloat) stuScore
? ? ? ? andStuSex:(NSString *) stuSex
? ? ? ? andStuAge:(NSInteger) stuAge{
? ? self = [super init];
? ? if (self) {
? ? ? ? _stuName = stuName;
? ? ? ? _stuScore = stuScore;
? ? ? ? _stuSex = stuSex;
? ? ? ? _stuAge = stuAge;
? ? }
? ? return self;
}
+(id)StudentWithName:(NSString *)stuName
?? ? ? ? andStuScore:(CGFloat) stuScore
?? ? ? ? ? andStuSex:(NSString *) stuSex
?? ? ? ? ? andStuAge:(NSInteger) stuAge{
? ? Student *stu = [[Student alloc] initWithName:stuName andStuScore:stuScore andStuSex:stuSex andStuAge:stuAge];
? ? return stu;
}
@end
main.m
Student *stu1 = [[Student alloc] initWithName:@"電腦" andStuScore:34.5 andStuSex:@"男" andStuAge:20];
? ? Student *stu2 = [[Student alloc] initWithName:@"鼠標" andStuScore:34.7 andStuSex:@"男" andStuAge:21];
? ? Student *stu3 = [[Student alloc] initWithName:@"鍵盤" andStuScore:45.6 andStuSex:@"nan" andStuAge:22];
? ? Student *stu4 = [[Student alloc] initWithName:@"顯示器" andStuScore:34.6 andStuSex:@"男" andStuAge:23];
? ? NSArray *stuArray1 = [[NSArray alloc]initWithObjects:stu1,stu2,stu3,stu4,nil];
?? ?
? ? NSArray *newArry = [stuArray1 sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
? ? ? ? Student *stu1,*stu2;
? ? ? ? stu1 = (Student *)obj1;
? ? ? ? stu2 = (Student *)obj2;
? ? ? ? return [stu1.stuName localizedCompare:stu2.stuName];
? ? }];
? ? NSLog(@"未排序前:");
? ? for (Student *stu in stuArray1) {
? ? ? ? NSLog(@"name = %@,score = %g,sex = %@,age = %ld",stu.stuName,stu.stuScore,stu.stuSex,stu.stuAge);
? ? }
? ? NSLog(@"排序后");
? ? for (Student *stu in newArry) {
? ? ? ? NSLog(@"name = %@,score = %g,sex = %@,age = %ld",stu.stuName,stu.stuScore,stu.stuSex,stu.stuAge);
? ? }
? ? return 0;
這樣做會有幾方面的優點:1 支持多個漢字按字母序排序(若第一個字的第一個字母同樣。則按第一個字的第二個字母比較,若第一個字的字母全然同樣,按第二個字的首字母繼續排序)。 2原本可能須要保存漢字拼音的地方。如今不須要了。
3 能夠通過對nickNameSortde進一步定制。完畢更復雜的比較,比方先比較會員狀態,在按姓名字母序完畢比較。4總體結構簡單 使用的都是CocaTouch框架下的的方法。
posted on 2017-08-07 20:42 mthoutai 閱讀(...) 評論(...) 編輯 收藏
轉載于:https://www.cnblogs.com/mthoutai/p/7301248.html
總結
以上是生活随笔為你收集整理的NSArray利用Cocoa框架进行汉字排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]Java中Runtime.exec
- 下一篇: UE4 AR开发笔记