NSNumber简介
NSNumber是数字的对象形式,因为在OC的数组和字典中只允许存放对象,所以我们有时候需要转化
我们普通的类型是 123 那么 NSNumber类型的是 @123,它是一个对象
1.把int float double等类型转化为 NSNumber类型
查看系统的API我们可以看见有如下的方法可以生成NSNumber类型:
+ (NSNumber *)numberWithChar:(char)value; + (NSNumber *)numberWithUnsignedChar:(unsigned char)value; + (NSNumber *)numberWithShort:(short)value; + (NSNumber *)numberWithUnsignedShort:(unsigned short)value; + (NSNumber *)numberWithInt:(int)value; + (NSNumber *)numberWithUnsignedInt:(unsigned int)value; + (NSNumber *)numberWithLong:(long)value; + (NSNumber *)numberWithUnsignedLong:(unsigned long)value; + (NSNumber *)numberWithLongLong:(long long)value; + (NSNumber *)numberWithUnsignedLongLong:(unsigned long long)value; + (NSNumber *)numberWithFloat:(float)value; + (NSNumber *)numberWithDouble:(double)value; + (NSNumber *)numberWithBool:(BOOL)value; + (NSNumber *)numberWithInteger:(NSInteger)value NS_AVAILABLE(10_5, 2_0); + (NSNumber *)numberWithUnsignedInteger:(NSUInteger)value NS_AVAILABLE(10_5, 2_0);
//1.把 int float double转化为对应的对象类 int aa1 = 110; NSNumber *aa2 = @(aa1);//直接使用@符号转化 NSNumber *aa3 = [NSNumber numberWithInt:aa1];//使用方法转化 float bb1 = 13.4; NSNumber *bb2 = [NSNumber numberWithFloat:bb1]; NSLog(@"aa2 = %@,bb2 = %@",aa2,bb2);
2.把 NSNumber转化为普通数据类型
我们可以通过NSNumber的属性和方法来获得其内部的值
@property (readonly) char charValue; @property (readonly) unsigned char unsignedCharValue; @property (readonly) short shortValue; @property (readonly) unsigned short unsignedShortValue; @property (readonly) int intValue; @property (readonly) unsigned int unsignedIntValue; @property (readonly) long longValue; @property (readonly) unsigned long unsignedLongValue; @property (readonly) long long longLongValue; @property (readonly) unsigned long long unsignedLongLongValue; @property (readonly) float floatValue; @property (readonly) double doubleValue; @property (readonly) BOOL boolValue; @property (readonly) NSInteger integerValue NS_AVAILABLE(10_5, 2_0); @property (readonly) NSUInteger unsignedIntegerValue NS_AVAILABLE(10_5, 2_0); @property (readonly, copy) NSString *stringValue;
//2.获取NSNumber中的数字值 NSNumber *cc1 = @123; int cc2 = [cc1 intValue];//获取整数值 NSNumber *dd1 = @123.456; double dd2 = [dd1 doubleValue];//获取double值 double dd3= dd1.intValue;//属性方式
- (NSComparisonResult)compare:(NSNumber *)otherNumber; - (BOOL)isEqualToNumber:(NSNumber *)number;4.NSNumber存放到 数组 或者 字典中
NSArray *arr = @[@1,@123,@2]; NSNumber *num1 = arr[0]; NSNumber *num2 = [arr objectAtIndex:1]; NSDictionary *dic = @{@"key1":@1,@"key2":@2}; NSNumber *nu1 = dic[@"key1"]; NSNumber *nu2 = [dic objectForKey:@"key2"];
原文地址:http://blog.csdn.net/yangbingbinga/article/details/46408585