Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)'


1 Answers

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

NSString *speedLabel = [[NSString alloc] initWithFormat:@"%.2f %@", speed, speedUnits];
like image 51
Daniel Barden Avatar answered Sep 12 '26 12:09

Daniel Barden



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!