在Objective-c中有int的数据类型,那为什么还要使用数字对象NSNumber?这是因为很多类(如NSArray)都要求使用对象,而int不是对象。
NSNumber就是数字对象,我们可以使用NSNumber对象来创建和初始化不同类型的数字对象。
创建NSNumber对象:
初始化NSNumber对象:
initWithChar:
initWithDouble:
initWithFloat:
initWithInt:
initWithInteger:
initWithLong:
initWithLongLong:
initWithShort:
initWithUnsignedChar:
initWithUnsignedInt:
initWithUnsignedInteger:
initWithUnsignedLong:
initWithUnsignedLongLong:
initWithUnsignedShort:
访问值:
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

1万+

被折叠的 条评论
为什么被折叠?



