DirTy™의 하루일과/DirTy™의 가당찮은iOS

[IOS] 타입간 형변환

DirTy™ 2015. 5. 8. 11:15


NSString to float, float to NSString

NSString *string = @"0.5";

float result = 0.3 + [string floatValue];

NSLog(@"result = %f", result);

NSLog(@"trimmedResult = %.1f", result);

NSString *floatResultToString = [NSString stringWithFormat:@"%f", result];

NSLog(@"floatResultToString = %@", floatResultToString);


NSString to Int, int to NSString

NSString *string2 = @"2";

int result2 = 3 + [string2 intValue];

NSLog(@"result2 = %d", result2);

NSString *intResultToString = [NSString stringWithFormat:@"%d", result2];

NSLog(@"intResultToString = %@", intResultToString); //Be sure to not using %d, it will cause unexpected error.


NSData to NSString, NSString to NSData

NSString *string3 = @"한글(any unicode character include Korean, Japanese, Chinese)";

NSData *aData = [string3 dataUsingEncoding:NSUTF8StringEncoding];

NSString *string4 = [[NSString alloc] initWithData:aData encoding:NSUTF8StringEncoding];

NSLog(@"string4 = %@", string4);


NSDate to NSString 

NSDate *today = [NSDate date];

//NSLog(@"todayDateString = %@", [today descriptionWithLocale:[NSLocale currentLocale]]);

NSLog(@"todayDateString = %@", [today description]); // it will return YYYY-MM-DD HH:MM:SS GMT

BOOL to NSString, NSString to BOOL

NSString *boolYesString = @"YES";

BOOL aBOOL = [boolYesString boolValue];

if (aBOOL) {

NSLog(@"aBOOL is YES");

}

Int to NSNumber

NSNumber *myNumber = [NSNumber numberWithInt:3];

NSLog(@"myNumber=%@", myNumber);



Double to NSString, NSString to Double

NSString *theString = @"123";

double theDouble = [theString doubleValue];

NSLog(@"theDouble = %f", theDouble);


NSString *doubleString = [NSString stringWithFormat:@"%f", theDouble];

NSLog(@"doubleString = %@", doubleString);


NSString *doubleString2Digit = [NSString stringWithFormat:@"%.2f", theDouble];

NSLog(@"doubleString with 2digit Decimal Point = %@", doubleString2Digit);


NSData to UIImage

NSData *imageData = UIImagePNGRepresentation(image);

UIImage *image=[UIImage imageWithData:data];


원문 : http://www.coverboy.co.kr/365