首页 > 代码库 > NSArray利用Cocoa框架进行汉字排序
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 = [superinit];
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 = [[Studentalloc] initWithName:stuNameandStuScore:stuScore andStuSex:stuSex andStuAge:stuAge];
return stu;
}
@end
main.mStudent *stu1 = [[Studentalloc]initWithName:@"电脑"andStuScore:34.5andStuSex:@"男"andStuAge:20];
Student *stu2 = [[Studentalloc] initWithName:@"鼠标"andStuScore:34.7andStuSex:@"男"andStuAge:21];
Student *stu3 = [[Studentalloc] initWithName:@"键盘"andStuScore:45.6andStuSex:@"nan"andStuAge:22];
Student *stu4 = [[Studentalloc] initWithName:@"显示器"andStuScore:34.6andStuSex:@"男"andStuAge:23];
NSArray *stuArray1 = [[NSArrayalloc]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.stuNamelocalizedCompare:stu2.stuName];
}];
NSLog(@"未排序前:");
for (Student *stuin stuArray1) {
NSLog(@"name = %@,score = %g,sex = %@,age = %ld",stu.stuName,stu.stuScore,stu.stuSex,stu.stuAge);
}
NSLog(@"排序后");
for (Student *stuin newArry) {
NSLog(@"name = %@,score = %g,sex = %@,age = %ld",stu.stuName,stu.stuScore,stu.stuSex,stu.stuAge);
}
return 0;
这样做会有几方面的优点:1 支持多个汉字按字母序排序(若第一个字的第一个字母同样。则按第一个字的第二个字母比較,若第一个字的字母全然同样,按第二个字的首字母继续排序)。 2原本可能须要保存汉字拼音的地方。如今不须要了。
3能够通过对nickNameSortde进一步定制。完毕更复杂的比較,比方先比較会员状态,在按姓名字母序完毕比較。4总体结构简单使用的都是CocaTouch框架下的的方法。
NSArray利用Cocoa框架进行汉字排序