一、NSNumber:
因为NSArray与NSDictionary中值能存放对象,不能存放基本数据类型,所以需要将基本数据类型转化为对象类型,就用到了NSNumber。同样的对象类型也能转化为基本数据类型,详细代码如下:
1 #import <Foundation/Foundation.h> 2 int main(int argc, const char * argv[]) { 3 @autoreleasepool { 4 int i = 10; 5 double d = 3.1; 6 char c = ‘5‘; 7 BOOL b = 1; 8 //基本数据类型转换成对象类型 9 NSNumber *intNum = [NSNumber numberWithInt:i]; 10 NSNumber *doubleNum = [NSNumber numberWithDouble:d]; 11 NSNumber *charNum = [NSNumber numberWithChar:c]; 12 NSNumber *boolNnum = [NSNumber numberWithBool:b]; 13 NSArray *arr = @[intNum,doubleNum,charNum,boolNnum]; 14 NSLog(@"%@",arr); 15 //对象类型转化为基本数据类型 16 int ii = [intNum intValue]; 17 double dd = [doubleNum doubleValue]; 18 char cc = [charNum charValue]; 19 BOOL bb = [boolNnum boolValue]; 20 NSLog(@"%d %f %c %d",ii,dd,cc,bb); 21 //基本数据类型转化为对象类型的简写 22 NSNumber *num1 = @10; 23 NSNumber *num2 = @(dd); 24 NSLog(@"%@ %@",num1,num2); 25 //注意:当@后面为变量时候一定要加括号,当为常量时候可以省略括号! 26 } 27 return 0; 28 }
输出结果:
1 2016-05-03 10:25:27.367 NSNumber与NSValue[19005:3404888] ( 2 10, 3 "3.1", 4 53, 5 1 6 ) 7 2016-05-03 10:25:27.368 NSNumber与NSValue[19005:3404888] 10 3.100000 5 1 8 2016-05-03 10:25:27.368 NSNumber与NSValue[19005:3404888] 10 3.1 9 Program ended with exit code: 0
时间: 2024-10-09 00:54:56