Object-C中的排序和Compare陷阱
来源:http://m.blog.csdn.net/blog/u011883764/38868097
Date : 2015-12-24
一.Compare陷阱
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 }
二.排序
数字排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//数字排序 - (void)sortNumber{ NSArray *originalArray = @[@"8",@"41",@"32",@"11",@"-1"]; //block比较方法,数组中可以是NSInteger,CGFloat等(需要转换) NSComparator finderSort = ^(id string1,id string2){ if ([string1 integerValue] > [string2 integerValue]) { return (NSComparisonResult)NSOrderedDescending; }else if ([string1 integerValue] < [string2 integerValue]){ return (NSComparisonResult)NSOrderedAscending; } else return (NSComparisonResult)NSOrderedSame; }; NSArray *resultArray = [originalArray sortedArrayUsingComparator:finderSort]; NSLog(@"排序结果:%@",resultArray); }
字符串排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//字符串排序 - (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:obj2 options:comparisonOptions range:range]; }; NSArray *resultArray2 = [charArray sortedArrayUsingComparator:sort]; NSLog(@"字符串排序%@",resultArray2); }
字典排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//字典排序 - (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 = [number1 compare:number2]; //return result == NSOrderedAscending; //降序 return result == NSOrderedDescending;//升序 }]; NSLog(@"OrderedDescending:%@", resultArray); }
自定义对象排序
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//自定义对象排序 - (void)sortCustomObject{ SLPerson *person1 = [[SLPerson alloc] init]; [person1 setName:@"ABCD"]; [person1 setAge:24]; SLPerson *person2 = [[SLPersonalloc]init]; [person2 setName:@"ACBD"]; [person2 setAge:22]; SLPerson *person3 = [[SLPerson alloc] init]; [person3 setName:@"ABDC"]; [person3 setAge:33]; SLPerson *person4 = [[SLPerson alloc] init]; [person4 setName:@"ACDB"]; [person4 setAge:22]; NSMutableArray *array = [NSMutableArray arrayWithObjects:person1, person3, person4, person2, nil]; NSSortDescriptor *sortDescriptor1 = [NSSortDescriptor sortDescriptorWithKey:@"age" ascending:YES]; //先按照age排序, NSSortDescriptor *sortDescriptor2 = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; //如果age相同,按照name排序,以此类推 NSArray *tempArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor1, sortDescriptor2, nil]]; for(NSInteger i =0; i < [tempArray count]; i++){ NSLog(@"%@--------%d\n", [[tempArray objectAtIndex:i] name], [[tempArray objectAtIndex:i] age]); } }
代码链接:http://download.csdn.net/detail/u011883764/7827311