学习目标
1.比较NSNumber的大小
2.-(BOOL) isEqualToNumber:
3.- (NSComparisonResult)compare:(NSNumber *)otherNumber;
学习过程
1.比较概述
<1>既然NSNumber都是数值型的封装,那么它们之间可以比较大小,
<2>不可使用比较运算符来比较,如,不可用>, <…..
2.NSNumber的实例方法: (BOOL)isEqualToNumber:(NSNumber *)number;
(1)比较两个NSNumber是否相等,相等返回YES,不相等返回NO;
比如[num1 isEqualToNumber:num2];
示例:下面示例打印结果为相等
void f1() {
NSNumber* num1 = [NSNumber numberWithInt:23];
NSNumber* num2 = [NSNumber numberWithFloat:23.0f];
BOOL b = [num1 isEqualToNumber:num2];
if (b) {
NSLog(@"相等");
}else {
NSLog(@"不相等");
}
}
3.NSNumber的方法 - (NSComparisonResult)compare:(NSNumber *)otherNumber;
(1)比较两个NSNumbe的大小,结果有三种<1>小<2>相等<3>大;
(2)原代码:
typedef NS_ENUM(NSInteger, NSComparisonResult)
{
NSOrderedAscending = -1L, //-1
NSOrderedSame, //0
NSOrderedDescending //1
};
(3) NSComparisonResult,这是一个枚举型,既然是枚举型,那么值就一定是整数比如[num1 compare:num2]; 如果num1小于num2返回NSOrderedAscending ,即long型的-1L; num1与mum2相等返回NSOrderedSame ,即long型的0L;num1大小mum2返回NSOrderedDescending ,即long型的1L。 示例:
void f2() {
NSNumber* num1 = [NSNumber numberWithInt:23];
NSNumber* num2 = [NSNumber numberWithFloat:23.0F];
NSComparisonResult r = [num1 compare:num2];
NSLog(@"r = %ld", r);//r = 0
if (r == NSOrderedAscending) {//可改为if(r == -1L)
NSLog(@"num1小于num2");
}else if(r == NSOrderedSame) {//可改为if(r == 0L)
NSLog(@"num1等于num2");
}else if(r == NSOrderedDescending) {//可改为if(r == 1)
NSLog(@"num1大于num2");
}
}