解析數(shù)據(jù)過程中經(jīng)常會遇見各種數(shù)據(jù)類型轉(zhuǎn)換的問題宙项,整理一下分享給大家名秀。
NSString:字符串類
NSString *newString = @"123"
// 1)字符串類型 轉(zhuǎn)化為 基本數(shù)據(jù)類型
NSInteger _intValue = [newString intValue];
NSLog(@"%ld", _intValue);
CGFloat _floatValue = [newString floatValue];
NSLog(@"%.2f", _floatValue);
// 2)基本數(shù)據(jù)類型 轉(zhuǎn)化為 字符串類型
NSString *intString = [NSString stringWithFormat:@"%d", _intValue];
NSLog(@"%@", intString);
NSString *floatString = [NSString stringWithFormat:@"%f", _floatValue];
NSLog(@"%@", floatString);
NSNumber:數(shù)值類
// 完成基本數(shù)據(jù)類型和數(shù)值類型的轉(zhuǎn)換
// 1)基本數(shù)據(jù)類型 轉(zhuǎn)化為 數(shù)值對象
NSNumber *intNumber = [NSNumber numberWithInteger:5];
NSLog(@"%@", intNumber);
NSNumber *charNumber = [NSNumber numberWithChar:'a'];
NSLog(@"%@", charNumber);
NSNumber *floatNumber = [NSNumber numberWithFloat:12.15];
NSLog(@"%@", floatNumber);
// 2)數(shù)值對象 轉(zhuǎn)化為 基本數(shù)據(jù)類型
NSInteger _intValue = [intNumber integerValue];
NSLog(@"%ld", _intValue);
CGFloat _floatValue = [floatNumber floatValue];
NSLog(@"%.2f", _floatValue);
char _charValue = [charNumber charValue];
NSLog(@"%c", _charValue);
// 3)數(shù)值對象 轉(zhuǎn)化為 字符串對象
// 假設(shè)現(xiàn)有一數(shù)值類型的變量A琼了,要轉(zhuǎn)換成字符串類型的B
NSNumberFormatter* numberFormatter = [[NSNumberFormatteralloc] init];
B = [numberFormatter stringFromNumber:A];
NSValue:結(jié)構(gòu)體對象類
// 結(jié)構(gòu)體變量 轉(zhuǎn)化為 NSValue對象
NSValue *point = [NSValue valueWithPoint:NSMakePoint(10, 20)];
NSLog(@"%@", point);
NSValue *size = [NSValue valueWithSize:NSMakeSize(320, 480)];
NSLog(@"%@", size);
NSValue *rect = [NSNumber valueWithRect:NSMakeRect(0, 0, 375, 667)];
NSLog(@"%@", rect);
// NSValue對象 轉(zhuǎn)化為 結(jié)構(gòu)體變量
NSPoint _pointVale = [point pointValue];
NSLog(@"%@", NSStringFromPoint(_pointVale));
NSSize _sizeValue = [size sizeValue];
NSLog(@"%@", NSStringFromSize(_sizeValue));
NSRect _rectValue = [rect rectValue];
NSLog(@"%@", NSStringFromRect(_rectValue));
// Format:萬能公式標(biāo)志
NSMutableString *string2 = [NSMutableString stringWithFormat:@"這是一個神奇的萬能公式,相當(dāng)實用"];
NSInteger number = 12345;
[string appendFormat:@"%ld", number];
NSLog(@"%@", string);