NSNumber 详解

在Objective-c中有int的数据类型,那为什么还要使用数字对象NSNumber?这是因为很多类(如NSArray)都要求使用对象,而int不是对象。
NSNumber就是数字对象,我们可以使用NSNumber对象来创建和初始化不同类型的数字对象。

创建NSNumber对象:

numberWithBool:


初始化NSNumber对象:
initWithBool:
initWithChar:
initWithDouble:
initWithFloat:
initWithInt:
initWithInteger:
initWithLong:
initWithLongLong:
initWithShort:
initWithUnsignedChar:
initWithUnsignedInt:
initWithUnsignedInteger:
initWithUnsignedLong:
initWithUnsignedLongLong:
initWithUnsignedShort:


访问值:
boolValue
charValue
decimalValue
doubleValue
floatValue
intValue
integerValue
longLongValue
longValue
shortValue
unsignedCharValue
unsignedIntegerValue
unsignedIntValue
unsignedLongLongValue
unsignedLongValue
unsignedShortValue

例如:
#import <Foundation/Foundation.h>

NSNumber *myNumber,*floatNumber,*intNumber,*number1;

//创建integer类型对象
intNumber = [NSNumber numberWithInteger:123];
NSLog(@"%i",[intNumber integerValue]);

//创建long类型对象
myNumber = [NSNumber numberWithLong:0xababab];
NSLog(@"%lx",[myNumber longValue]);

//创建char类型对象
myNumber = [NSNumber numberWithChar:'K'];
NSLog(@"%c",[myNumber charValue]);

//创建float类型对象
floatNumber = [NSNumber numberWithFloat:123.00];
NSLog(@"%f",[floatNumber floatValue]);

//创建double类型对象
myNumber = [NSNumber numberWithDouble:112233e+15];
NSLog(@"%lg",[myNumber doubleValue]);

//判断两个对象的值是否相等
if ([intNumber isEqualToNumber:floatNumber] == YES ) {
   NSLog(@"值相等");
} else {
   NSLog(@"值不相等");
}

//比较两个对象的值大小
if ( [intNumber compare:myNumber] == NSOrderedAscending) {
   NSLog(@"左边的数字小");
} else {
   NSLog(@"左边的数字大");
}

//初始化实例
number1 = [[NSNumber alloc] initWithInt:1000];
NSLog(@"%d",[number1 intValueunsigned];
[number1 release];



检索字符串表示:

返回一个字符串表示对于一个给定的数字对象内容的现场:

- (NSString *)descriptionWithLocale:(id)aLocale

比较NSNumber对象:

比较两个对象的大小:

- (NSComparisonResult)compare:(NSNumber *)aNumber

[intNumber compare:myNumber]

两个数进行比较大小,

如果值恒等于  NSOrderedAscending  表示intNumber小于myNumber

NSOrderedSame表示相等

NSOrderedDecending表示前一个大于后一个。


比较的是对象中存储的数据:

- (BOOL)isEqualToNumber:(NSNumber *)aNumber

NSNumber *num2 = [[NSNumber alloc] initWithFloat:10.5];

//isEqualToNumber: 比较的是对象中存储的数据

BOOL isEqual = [num1 isEqualToNumber:num2];

NSLog(@"isEqual=%d", isEqual);

类型信息:
- (const char *)objCType



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值