标签:ott name pos int result nic ext atomic nan
在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框架下的的方法。
标签:ott name pos int result nic ext atomic nan
原文地址:http://www.cnblogs.com/mthoutai/p/7301248.html