[Objective-C] 타입간 변환 (형변환, 데이터타입 변환)
최고관리자
2019.01.30 17:05
4,622
0
본문
문자를 숫자로 ( String -> int, float, double, ... )
NSString *aString = @"111";
int aInt = [aString intValue];
float aFloat = [aString floatValue];
double aDouble = [aString doubleValue];
NSLog(@"aInt = %d", aInt);
NSLog(@"aFloat = %f", aFloat);
NSLog(@"aDouble = %d", aDouble);
숫자를 문자로 ( int, float, double, ... -> String )
아래와 같이 stringWithFormat을 이용한다.
NSString* aIntStr = [NSString stringWithFormat:@"%d", aInt];
============================================================
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];
출처: https://comxp.tistory.com/238 [까칠하게...]
댓글목록 0