Objective-C中NSString转换成BOOL类型

一、问题

在开发中经常会遇到将字符串类型转换成BOOL类型的情况

比如:服务器下发“0” 或 “1” ,客户端转换成 NO 或 “YES”

一般我们会直接调用 [NSString boolValue] 方法来得到结果,有时候可能结果不正确

二、方法解析

先看下官方文档的描述如下:

This property is YES on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. This property is NO if the receiver doesn’t begin with a valid decimal text representation of a number.

The property assumes a decimal representation and skips whitespace at the beginning of the string. It also skips initial whitespace characters, or optional -/+ sign followed by zeroes.

大致意思就是说:

忽略开头的空字符,以 "Y", "y", "T", “t”,1-9开头的字符串都为真,其他都为假 特殊情况 如果全是数字,只要有一个非0的就是真

下面是我测试的结果:

NSArray *tests = @[ @"Y",       //YES
                    @"N",       //NO
                    @"T",       //YES
                    @"F",       //NO
                    @"t",       //YES
                    @"f",       //NO
                    @"1",       //YES
                    @"0",       //NO
                    @"Yes",     //YES
                    @"No",      //NO
                    @"AY",      //NO
                    @"NY",      //NO
                    @"YN",      //YES
                    @"No not YES", //NO
                    @"true",    //YES
                    @"false",   //NO
                    @"To be or not to be", //YES
                    @"False",    //NO
                    @"3567",        //YES
                    @"0123456789"  //YES
                    @“000",  //NO
                    ];
三、结论

所以,如果下发了错误的数据,一不小心就会出错了,最佳实践就是尽量别用这个方法,Json本身就是支持bool类型的,如果用也只用 “1”,“0”,“true”,”false” 这几个字符串来转换

参考资料:

1、官方文档

2、[NSString boolValue]