IOS> NSString 常见数据类型转换:转NSInteger , NSDate(互转)

1. NSString转NSInteger, 转int (float, double类似 )

1.1正常情况 , NSString所包含内容确能转化为int的类型

NSString *sNumber = @"123";
NSInteger lNumber = [sNumber integerValue];
int iNumber = [sNumber intValue];
NSLog(@"字符串NSString: %@\n转换后-->\n长整型(64bit long): %ld\n整型(32bit int):%d", sNumber, (long)lNumber, (int)iNumber);

执行结果

字符串NSString: 123
转换后-->
长整型(64bit long): 123
整型(32bit int):123

 

1.2非正常情况 , NSString 包含不能转化为int的字符串

NSString *sNumber = @"123abc";
NSInteger lNumber = [sNumber integerValue];
int iNumber = [sNumber intValue];
NSLog(@"\n1. 字符串NSString: %@\n转换后-->\n长整型(64bit long): %ld\n整型(32bit int):%d", sNumber, (long)lNumber, (int)iNumber);
        
NSString *sNumber2 = @"12a3bc";
NSInteger lNumber2 = [sNumber2 integerValue];
int iNumber2 = [sNumber2 intValue];
NSLog(@"\n2. 字符串NSString: %@\n转换后-->\n长整型(64bit long): %ld\n整型(32bit int):%d", sNumber2, (long)lNumber2, (int)iNumber2);
        
NSString *sNumber3 = @"1a23bc";
NSInteger lNumber3 = [sNumber3 integerValue];
int iNumber3 = [sNumber3 intValue];
NSLog(@"\n3. 字符串NSString: %@\n转换后-->\n长整型(64bit long): %ld\n整型(32bit int):%d", sNumber3, (long)lNumber3, (int)iNumber3);
        
NSString *sNumber4 = @"a123bc";
NSInteger lNumber4 = [sNumber4 integerValue];
int iNumber4 = [sNumber4 intValue];
NSLog(@"\n4. 字符串NSString: %@\n转换后-->\n长整型(64bit long): %ld\n整型(32bit int):%d", sNumber4, (long)lNumber4, (int)iNumber4);

执行结果

1. 字符串NSString: 123abc
转换后-->
长整型(64bit long): 123
整型(32bit int):123
2015-07-20 22:18:24.1872. 字符串NSString: 12a3bc
转换后-->
长整型(64bit long): 12
整型(32bit int):12
2015-07-20 22:18:24.1873. 字符串NSString: 1a23bc
转换后-->
长整型(64bit long): 1
整型(32bit int):1
2015-07-20 22:18:24.1874. 字符串NSString: a123bc
转换后-->
长整型(64bit long): 0
整型(32bit int):0

可以看到,并没有报错,而且能转化的字符串能到第一个非数字字符为止。

 

2. NSInteger转NSString: +stringWithFormat

NSInteger lNumber = 1200l;
NSString* sNumber = [NSString stringWithFormat:@"%ld", lNumber];
NSLog(@"\n长整型(64bit long): %ld\n转换后-->\nNSString: %@", (long)lNumber, sNumber);

执行结果

长整型(64bit long): 1200
转换后-->
NSString: 1200

 

3.NSString转NSDate

(未完待续)...

 

posted @ 2015-07-20 23:47  明明1109  阅读(3978)  评论(0编辑  收藏  举报