iOS开发——NSString、NSNumber等类型间的相互转换

NSNumber转NSString

NSString *A = [[NSString alloc] init];
NSNumber *B = [NSNumber numberWithInt:123456];
A = [NSString stringWithFormat:@"%@",B];

NSString转NSNumber

NSString *A = @"890909";
NSNumber *B = @([A integerValue]);

NSString转int

NSString *A = @"123456";
int B = [A intValue];

int转NSString

int B = 123;
NSString *A = [NSString stringWithFormat:@"%d",B];

NSString转NSData

NSData *A = [@"textString" dataUsingEncoding:NSUTF8StringEncoding];

NSData转NSString

NSData *A;
NSString *B=[[NSString alloc] initWithData:A  encoding:NSUTF8StringEncoding];

NSString转NSDate(日期类,不是NSData)

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *A = @"2017-06-03 11:20:05";
NSDate *date = [dateFormatter dateFromString:A];

NSDate转NSString

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *B = [NSDate date];//系统现在的时间
NSString *A = [dateFormatter stringFromDate:B];

NSRange转NSValue

  • 开发中可能需要将range存进数组中或者字典中,此时需要把NSRange(结构体)转成NSObject对象
NSRange range = NSMakeRange(1,1);
NSValue *value = [NSValue valueWithRange:range];

NSValue转NSRange

NSRange range = [value rangeValue];

更新中....

推荐阅读更多精彩内容