[NSString boolValue]

来源:互联网 发布:windows pe u盘版 编辑:程序博客网 时间:2024/06/04 15:53

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 someHidden 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 aBOOL 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:

stringboolValueYYESNNOTYESFNOtYESfNO1YES0NOYesYESNoNONo really noNOtrueYESfalseNOTo be or not to beYESFalseNO3567YES0123456789NO

With this snippet , you can to check the results:

#import <Foundation/Foundation.h>// clang -g -framework Foundation -o bool bool.mint 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, checkNSHipster , I promisse you will learn a lot…


0 0