NSScanner
NO
如果没有找到有效的字符串,将根据其验证规则返回:
十六进制整数表示可以可选地以 0x 或 0X 开头。
这是演示这一点的示例代码:
NSString *valid1 = @"ae";
NSString *valid2 = @"0xae";
NSString *valid3 = @"0Xae";
NSString *invalid1 = @"ze";
NSString *invalid2 = @"hello";
void (^scanBlock)(NSString *) = ^(NSString *toScan) {
NSScanner *scanner = [NSScanner scannerWithString:toScan];
UInt32 parsed = 0;
BOOL success = [scanner scanHexInt:&parsed];
NSLog(
@"Scanner %@ able to scan the string %@. parsed's value is %x",
success ? @"was" : @"wasn't",
toScan,
parsed);
};
for (NSString *valid in @[ valid1, valid2, valid3]) {
scanBlock(valid);
}
for (NSString *invalid in @[invalid1, invalid2]) {
scanBlock(invalid);
}
上述代码的输出是:
Scanner was able to scan the string ae. parsed's value is ae
Scanner was able to scan the string 0xae. parsed's value is ae
Scanner was able to scan the string 0Xae. parsed's value is ae
Scanner wasn't able to scan the string ze. parsed's value is 0
Scanner wasn't able to scan the string hello. parsed's value is 0
但是,由于其灵活的性质,NSScanner
不会应用超出其立即扫描位置的验证规则。它还将某些字符串视为无效,而其他人可能认为是有效的十六进制字符串。例如:
NSString *greyArea1 = @"x23";
NSString *greyArea2 = @"artichoke";
NSString *greyArea3 = @"1z";
NSString *greyArea4 = @" a3";
for (NSString *grey in @[greyArea1, greyArea2, greyArea3, greyArea4]) {
scanBlock(grey);
}
Even though these strings are invalid for an application that expects input to strictly be a string representing a hexadecimal number and nothing else, and some people may consider "x23" a valid hex string, this code gives the following output:
Scanner wasn't able to scan the string x23. parsed's value is 0
Scanner was able to scan the string artichoke. parsed's value is a
Scanner was able to scan the string 1z. parsed's value is 1
Scanner was able to scan the string a3. parsed's value is a3
Since Java's Integer
class and NSScanner
have such different purposes, the rules they apply to validate strings are much different, and I think that's the root of your problem. If you do wish to use NSScanner
, then you will have to apply validation rules that make sense for your application that would interfere with NSScanner
's general operation.