NSNumber作用:
将基本数据类型转变成对象
NSNumber
NSNumber *intNumber = [[NSNumber alloc] initWithInt: 5]; //将整形5转换为对象5
NSNumber *floatNumber = [[NSNumber alloc] initWithFloat: 3.14f]; //将浮点型转换为对象
NSNumber *doubleNumber = [[NSNumber alloc] initWithDouble: 6.7];
NSNumber *charNumber = [[NSNumber alloc] initWithChar: 'A'];
为什么要作这样的转化:
比如下面的两个整形比较大小,就需要使用方法
NSNumber *intNumber1 = [[NSNumber alloc] initWithInt: 6];
NSNumber *intNumber2 = [[NSNumber alloc] initWithInt: 7];
BOOL ret = [intNumber1 isEqualToNumber:intNumber2];
NSLog(@"%d", ret);
if ([intNumber1 compare: intNumber2] == NSOrderedAscending)
{
NSLog(@"<")
}
else if ([intNumber1 compare: intNumber2] == NSOrderedSame)
{
NSLog(@"==");
}
else if ([intNumber1 compare: intNumber2] == NSOrderedDescending)
{
NSLog(@">");
}
还原基本数据类型的数据:
NSLog(@"%d", [intNumber intValue]);
NSLog(@"%f", [floatNumber floatValue]);
NSLog(@"%f", [doubleNumber doubleValue]);
NSLog(@"%c", [charNumber charValue]);
|
|