How to parse NSString into BOOL in Objective-C?

Objective CCocoaNsstringBoolean

Objective C Problem Overview


I am programming in Objective-C for iOS. I would like to parse an object of type NSString into a scalar of type BOOL.

I have a value, and I know that it will either be @"YES" or @"NO", but that YES (or) NO value is NSString and I just want to change NSString into BOOL.

How can I do that?

Please answer me if you know.

Thanks for reading.

Objective C Solutions


Solution 1 - Objective C

I think it's this:

BOOL boolValue = [myString boolValue];

Solution 2 - Objective C

You should probably use NSString's -boolValue. To quote the documentation directly:

> [Returns t]he Boolean value of the receiver’s text. Returns YES on > encountering one of "Y", "y", "T", "t", or a digit 1-9—the method > ignores any trailing characters. Returns NO if the receiver doesn’t > begin with a valid decimal text representation of a number.

That would seem to match your input cases.

Solution 3 - Objective C

if ([string isEqualToString: @"YES"])
  foo();
else
  bar();

Solution 4 - Objective C

This would probably best be solved with a conditional, for example:

if ([myString isEqualToString:@"YES"])
    myBool = YES;
else if ([myString isEqualToString:@"NO"])
    myBool = NO;

Hope this helped you, good luck with your programming.

Solution 5 - Objective C

This property should also return true if string is 'true' that's why i think extension is needed...

extension NSString{
 var boolValueExtended: Bool {
    get{
        return boolValue ||
            self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).uppercaseString == "TRUE"
    }
}

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFire FistView Question on Stackoverflow
Solution 1 - Objective CbschultzView Answer on Stackoverflow
Solution 2 - Objective CTommyView Answer on Stackoverflow
Solution 3 - Objective Cuser23743View Answer on Stackoverflow
Solution 4 - Objective CMarcus BuffettView Answer on Stackoverflow
Solution 5 - Objective CYanView Answer on Stackoverflow