在NSString有一個函數localizedCompare:,它的功能是經過自身與給定字符串的比較,返回一個本地化的比較結果。也就是說這個函數是支持漢字比較的。框架
Student.h
@interface Student : NSObject函數
@property(nonatomic,copy)NSString *stuName;post
@property(nonatomic,assign)CGFloat stuScore;atom
@property(nonatomic,copy)NSString *stuSex;spa
@property(nonatomic,assign)NSInteger stuAge;3d
-(id)initWithName:(NSString *)stuName排序
andStuScore:(CGFloat) stuScore字符串
andStuSex:(NSString *) stuSexit
andStuAge:(NSInteger) stuAge;io
+(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框架下的的方法。