Objective-C之基本数据类型

1 基本数据类型示例

//整型
int integerType = 5;
//浮点型
float floatType = 3.1415;
//双浮点型
double doubleType = 2.2033;
//短整型
short int shortType = 200;
//长整型
long int longlongType = 7758123456767L;
//c语言字符串
char * cstring = "this is a string!";

2 基本数据类型长度

// 4字节
NSLog(@"The size of an int is: %ld bytes",sizeof(int));
//2字节
NSLog(@"The size of an short int is: %ld bytes",sizeof(short int));
//8字节
NSLog(@"The size of an long int is: %ld bytes",sizeof(long int));
//1字节
NSLog(@"The size of an char is: %ld bytes",sizeof(char));
//4字节
NSLog(@"The size of an float is: %ld bytes",sizeof(float));
//8字节
NSLog(@"The size of an double is: %ld bytes",sizeof(double));
//1字节
NSLog(@"The size of an bool is: %ld bytes",sizeof(bool));

3 格式化输出数据

//整型
NSLog(@"The value of integerType = %d.",integerType);

//浮点型
NSLog(@"The value of integerType = %.2f.",floatType);

//double型
NSLog(@"The value of integerType = %e.",doubleType);

//短整型
NSLog(@"The value of integerType = %d.",shortType);

//长整形
NSLog(@"The value of integerType = %ld.",longlongType);

//c语言字符串
NSLog(@"The value of integerType = %s.",cstring);

打印结果:

2016-10-09 17:07:01.375231 OcDemo[12845:1095736] 格式化输出数据
2016-10-09 17:07:01.375249 OcDemo[12845:1095736] The value of integerType = 5.
2016-10-09 17:07:01.375302 OcDemo[12845:1095736] The value of integerType = 3.14.
2016-10-09 17:07:01.375319 OcDemo[12845:1095736] The value of integerType = 2.203300e+00.
2016-10-09 17:07:01.375329 OcDemo[12845:1095736] The value of integerType = 200.
2016-10-09 17:07:01.375337 OcDemo[12845:1095736] The value of integerType = 7758123456767.
2016-10-09 17:07:01.375362 OcDemo[12845:1095736] The value of integerType = this is a string!.

4 int,NSInteger,NSUInteger,NSNumber

  • 当需要使用int类型的变量的时候,可以像写C的程序一样,用int,也可以用NSInteger,但更推荐使用NSInteger,因为这样就不用考虑设备是32位的还是64位的。

  • NSUInteger是无符号的,即没有负数,NSInteger是有符号的。

  • NSInteger是基础类型,但是NSNumber是一个类。如果想要在NSMutableArray里存储一个数值,直接用NSInteger是不行的。

//基本数据类型封装到NSNumber类中
NSNumber *num = [NSNumber numberWithInt:88];
//NSNumber示例取出基本类型数据
NSInteger integer = [num intValue];

5 NSString与NSInteger的相互转换

NSInteger integerNumber = 888;NSString * string = [NSString stringWithFormat:@"%d",integerNumber];
NSLog(@"string is %@", string);integer = [string intValue];NSLog(@"integer is%d", integerNumber);
    原文作者:刘涤生
    原文地址: https://segmentfault.com/a/1190000007115318
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞