首页 > 代码库 > Objective—C中的排序及Compare陷阱
Objective—C中的排序及Compare陷阱
campare陷阱
NSString有多个compare相关方法:
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask range:(NSRange)compareRange locale:(id)locale;
NSComparisonResult 是定义的一个枚举,定义如下:
typedef NS_ENUM(NSInteger, NSComparisonResult) {NSOrderedAscending = -1L, NSOrderedSame, NSOrderedDescending};
其中,NSOrderedSame 表示比较的两个字符串完全一致, 同时,在这个枚举中,它的值是 0.
字符串比较在程序中很常见,比如:
if ([str1 compare:@"some text"] == NSOrderedSame) {
// TODO
}
else {
// TODO
}
但是,如果如上中的str1为nil,根据Objective-C的消息调用规则(方法调用),对nil发送的任何消息,得到的返回都是nil。这样的情况下,运行时是不会像C/C++那样,出现空指针的非法访问而使得程序强行终止。也就是说,在Objective-C下面,即便str1为nil,也不会造成程序崩溃,而是会继续运行。
那么当str1为空的时候,[str1 compare:@"some text"] 消息的返回就会为nil。nil表示一个空的Objective-C对象,实际就是表示一个空指针,而它代表的值就是0,与NSOrderedSame的值相等. 如此,回到最前面的if语句,如果str1为nil,那么整个语句的值为真。这会给程序造成非常严重的问题,小则逻辑错误,UI显示错误等,大则会造成数据泄漏等等。。。所以,一旦出现这种情况,还是很严重的。
笔者个人建议,以上代码至少应该写为:
if (str1!=nil && [str1 compare:@"some text"] == NSOrderedSame) {
// TODO
}
else {
// TODO
}
OC排序代码,直接上代码
//数字排序
- (void)sortNumber{
NSArray *originalArray = @[@"8",@"41",@"32",@"11",@"-1"];
//block比较方法,数组中可以是NSInteger,CGFloat等(需要转换)
NSComparator finderSort = ^(id string1,id string2){
if ([string1 integerValue] > [string2integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}else if ([string1integerValue] < [string2integerValue]){
return (NSComparisonResult)NSOrderedAscending;
}
else
return (NSComparisonResult)NSOrderedSame;
};
NSArray *resultArray = [originalArray sortedArrayUsingComparator:finderSort];
NSLog(@"排序结果:%@",resultArray);
}
//字符串排序
- (void)sortString{
// 2. 非数字型字符串(注意用compare比较要剔除空数据(nil))
NSArray *charArray =@[@"string 1",@"String 21",@"string 12",@"String 11",@"String 02"];
NSStringCompareOptions comparisonOptions =NSCaseInsensitiveSearch|NSNumericSearch|
NSWidthInsensitiveSearch|NSForcedOrderingSearch;
NSComparator sort = ^(NSString *obj1,NSString *obj2){
NSRange range = NSMakeRange(0,obj1.length);
return [obj1 compare:obj2options:comparisonOptionsrange:range];
};
NSArray *resultArray2 = [charArray sortedArrayUsingComparator:sort];
NSLog(@"字符串排序%@",resultArray2);
}
//字典排序
- (void)sortDicrionary{
NSMutableArray *array = [NSMutableArrayarrayWithObjects:
@{@"obj0":@"0"},
@{@"obj3":@"3"},
@{@"obj1":@"1"},
@{@"obj2":@"2"},
@{@"obj4":@"4"},
nil];
NSArray *resultArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2) {
NSNumber *number1 = [[obj1 allKeys] objectAtIndex:0];
NSNumber *number2 = [[obj2 allKeys] objectAtIndex:0];
NSComparisonResult result = [number1compare:number2];
//return result == NSOrderedAscending; //降序
return result == NSOrderedDescending;//升序
}];
NSLog(@"OrderedDescending:%@", resultArray);
}
//自定义对象排序
- (void)sortCustomObject{
SLPerson *person1 = [[SLPersonalloc]init];
[person1 setName:@"ABCD"];
[person1 setAge:24];
SLPerson *person2 = [[SLPersonalloc]init];
[person2 setName:@"ACBD"];
[person2 setAge:22];
SLPerson *person3 = [[SLPersonalloc]init];
[person3 setName:@"ABDC"];
[person3 setAge:33];
SLPerson *person4 = [[SLPersonalloc]init];
[person4 setName:@"ACDB"];
[person4 setAge:22];
NSMutableArray *array = [NSMutableArrayarrayWithObjects:person1, person3, person4, person2,nil];
NSSortDescriptor *sortDescriptor1 = [NSSortDescriptorsortDescriptorWithKey:@"age"ascending:YES]; //先按照age排序,
NSSortDescriptor *sortDescriptor2 = [NSSortDescriptorsortDescriptorWithKey:@"name"ascending:YES]; //如果age相同,按照name排序,以此类推
NSArray *tempArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil]];
for(NSInteger i =0; i < [tempArraycount]; i++){
NSLog(@"%@--------%d\n", [[tempArrayobjectAtIndex:i]name], [[tempArrayobjectAtIndex:i]age]);
}
}
代码链接:http://download.csdn.net/detail/u011883764/7827311
Objective—C中的排序及Compare陷阱