If you don’t know NSHipster , you’re missing a real gem among Cocoa blogs. Mattt Thompson has created this journal to weekly lighten unknown Cocoa / Cocoa Touch classes. And Mattt was even on stage at the WWDC 2013, presenting some Hidden Gems in Cocoa and Cocoa Touch .
As a tribute to NSHipster, let me present [NSString boolValue] . Every tailored iOS developer should know this method that converts a BOOL from a NSString .
Reading from the doc :
boolValue
Returns the Boolean value of the receiver’s text.
- (BOOL)boolValue
Return Value
The 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.
So booValue can scan and produce these outputs from the followings strings input:
string | boolValue |
---|---|
Y | YES |
N | NO |
T | YES |
F | NO |
t | YES |
f | NO |
1 | YES |
0 | NO |
Yes | YES |
No | NO |
No really no | NO |
true | YES |
false | NO |
To be or not to be | YES |
False | NO |
3567 | YES |
0123456789 | NO |
With this snippet , you can to check the results:
#import <Foundation/Foundation.h>
// clang -g -framework Foundation -o bool bool.m
int main (void)
{
NSArray *tests = @[ @"Y",
@"N",
@"T",
@"F",
@"t",
@"f",
@"1",
@"0",
@"Yes",
@"No",
@"No really no",
@"true",
@"false",
@"To be or not to be",
@"False",
@"3567",
@"0123456789"
];
NSArray *boolToString = @[@"NO", @"YES"];
for (NSString *test in tests){
NSLog(@"boolValue:\"%@\" => %@", test, boolToString[[test boolValue]]);
}
return 0;
}
Super minimalist and smart algorithm, you can also use boolValue ’s companion: doubleValue , floatValue , intValue , integerValue , longLongValue . If you didn’t learn anything, check NSHipster , I promisse you will learn a lot…