我在使用'initWithFormat'创建字符串时遇到了一些问题。这是我正在使用的代码:
- (void)convertSpeedUnits
{
NSString *speedUnits = [[NSUserDefaults standardUserDefaults] stringForKey:kSpeedUnits];
double speed;
if ([speedUnits isEqualToString:@"Knots"])
{
speed = ms2knots(currentSpeedMS);
}
else if ([speedUnits isEqualToString:@"MPH"])
{
speed = ms2kph(currentSpeedMS);
}
else if ([speedUnits isEqualToString:@"KPH"])
{
speed = ms2mph(currentSpeedMS);
}
NSString *speedLabel = [[NSString alloc] initWithFormat:@"%.2f %s", speed, speedUnits];
currentSpeed.text = speedLabel;
[speedLabel release];
}
我希望speedLabel
能够像这样......
'1.12结'或'1.12 MPH'或'1.12 KPH'
然而,我得到的是以下
'1.12(null)'
答案 0 :(得分:9)
speedUnits
是一个NSString,因此您应该使用%@
而不是%s
:
NSString *speedLabel = [[NSString alloc] initWithFormat:@"%.2f %@", speed, speedUnits];