我在使用'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(空)'

最佳答案

speedUnits是一个NSString,因此您应该使用%@而不是%s

NSString *speedLabel = [[NSString alloc] initWithFormat:@"%.2f %@", speed, speedUnits];

关于iphone - NSString initWithFormat用(null)产生值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7786018/

10-08 20:40