user843337
user843337

Reputation:

NSString initWithFormat producing value with (null)

I'm having some issues creating a string using 'initWithFormat'. Here is the code I'm using:

- (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];
}

I would expect speedLabel to be something like this...

'1.12 Knots' or '1.12 MPH' or '1.12 KPH'

however what I'm getting is the following

'1.12 (null)'

Upvotes: 2

Views: 5472

Answers (1)

Daniel Barden
Daniel Barden

Reputation: 1024

speedUnits is a NSString, so you should use %@ and not %s:

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

Upvotes: 9

Related Questions