iOS目标c substringToIndex崩溃

Lê *_*inh 2 objective-c ios

嗨,我正在使用一个带有一些验证规则的旧项目.

我的问题是几乎没有条形码扫描字符串,具有较小的特定字符.程序将崩溃以下代码行

if ([[sBarcodeValues substringToIndex:6] isEqualToString:@"2C2C2P"]){

}
Run Code Online (Sandbox Code Playgroud)

这是错误日志(下面是图片包含详细信息)

2016-12-22 14:51:56.019324 SAMKiosk[1008:476815] -[ScanAndPayVC checkBarCodeDetail]: sBarcodeValues 11.10
2016-12-22 14:51:56.019839 SAMKiosk[1008:476815] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSTaggedPointerString substringToIndex:]: Index 6 out of bounds; string length 5'
*** First throw call stack:
(0x1889611b8 0x18739855c 0x188961100 0x189386e80 0x1002ad930 0x1002a8320 0x1002a5bb8 0x19019ca54 0x19019c5f0 0x18b2b1d94 0x18b2d0dcc 0x10070d218 0x100719334 0x100727f94 0x10070f300 0x10071a8ac 0x100710ce0 0x10071205c 0x18890e810 0x18890c3fc 0x18883a2b8 0x18a2ee198 0x18e87a7fc 0x18e875534 0x1000e0414 0x18781d5b8)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

可能是因为字符串在检查需要时只包含5个字符.6.我们如何防止这种崩溃发生?帮助非常感谢.谢谢

rma*_*ddy 5

你是正确的,任何时候崩溃都会sBarcodeValues少于6个字符.

您可以添加额外的长度检查:

if (sBarcodeValues.length >= 6 && [[sBarcodeValues substringToIndex:6] isEqualToString:@"2C2C2P"]) {
}
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地做:

if ([sBarcodeValues hasPrefix:@"2C2C2P"]) {
}
Run Code Online (Sandbox Code Playgroud)

无论多长时间,这都会有效sBarcodeValues.