Edited at

(いまさら)Objective-C 型変換まとめ

More than 3 years have passed since last update.


NSInteger → NSString

NSInteger num = 10;

NSString *str = [NSString stringWithFormat:@"%d", num];


NSString → NSInteger

NSString *str = @"1500";

NSInteger num = [str intValue];


NSDate → NSString

NSDateFormatter * fmt = [NSDateFormatter new];

fmt.dateFormat = @"yyyy-MM-dd 'at' HH:mm";
NSDate *date = [NSDate date];
NSString *str = [fmt stringFromDate:date];

※きちんとしたNSDateを渡さないと、nilが返る


NSString → NSDate

NSDateFormatter *fmt = [NSDateFormatter new];

[fmt setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
NSString *str = @"2000/01/02 03:04:05";
NSDate *date = [fmt dateFromString:str];

※(おそらく)フォーマットと文字列がそろっていないと、nilが返る


NSData → NSString

NSData *data = // なんらかのデータを代入

NSString *str= [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


NSString → NSData

NSString *str = @"hoge";

NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];


NSNumber → NSString

[@10 stringValue];


NSStirng → NSNumber

[@"hoge" intValue];


NSStirng → char*

(char *) [str UTF8String]


char* → NSString

char *cp = "hoge";

NSString *str = [NSString stringWithCString: cp encoding:NSUTF8StringEncoding];