How to parse boolean into NSString

16,231

Boolean is basically an integer, so you can use %i to get its decimal representation. What you usually want is this:

NSString *booleanString = (value) ? @"True" : @"False";

Share:
16,231
JavaCake
Author by

JavaCake

Updated on June 06, 2022

Comments

  • JavaCake
    JavaCake almost 2 years

    I have following method that does some stringbuilding, but unfortunately i am having problem with parsing the boolean to my NSString.

    The code is following:

    - (void)setToolOutput:(int) outputNumber state: (BOOL) value {
        NSString *str =  [NSString stringWithFormat:@"this=%i is=%c",outputNumber,value];
        NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [OutputStream write:[data bytes] maxLength:[data length]];
        NSLog(@"%@", str);
    }
    

    I have tried to parse it by using %c for char, and %s as string of chars. Both ways outputs my boolean as a question mark turned upside down.

    EDIT: I want it to parse as True or False.

  • JavaCake
    JavaCake about 12 years
    I have tried this already, i get an exception according to @Paul.s
  • joerick
    joerick about 12 years
    I think this is one of the very few cases where the ternary expression is stylistically preferable
  • Paul.s
    Paul.s about 12 years
    @joerick that's a very broad statement, there are plenty of times when a ternary operator will clean things up without losing readability