Fire Fist
Fire Fist

Reputation: 7050

How to parse NSString into BOOL in Objective-C?

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.

Upvotes: 55

Views: 43074

Answers (5)

Yan
Yan

Reputation: 1727

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"
    }
}

}

Upvotes: 0

Marcus Buffett
Marcus Buffett

Reputation: 1389

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.

Upvotes: 0

Tommy
Tommy

Reputation: 100622

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.

Upvotes: 22

bschultz
bschultz

Reputation: 4254

I think it's this:

BOOL boolValue = [myString boolValue];

Upvotes: 157

user23743
user23743

Reputation:

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

Upvotes: 2

Related Questions