简体   繁体   English

iOS Objective C substringToIndex崩溃

[英]iOS Objective C substringToIndex crash

I'm working with an old project with some validation rule. 我正在使用具有某些验证规则的旧项目。

My problem with few barcode scanning string which has lesser then certain character. 我的问题是条形码扫描字串少,但字符数少。 The program will crash for the following line of code 该程序将因以下代码行而崩溃

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

}

Here is the error log (below is picture contain detail): 这是错误日志(下面的图片包含详细信息):

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) 

在此处输入图片说明

Maybe because string is only contain 5 characters when the checking require 6. How can we prevent this crashing happen? 可能是因为当检查要求6时,字符串仅包含5个字符。如何防止这种崩溃的发生?

You are correct that the crash will happen anytime sBarcodeValues is less than 6 characters. 您很正确地认为, sBarcodeValues少于6个字符,就会发生崩溃。

You can add an additional check for the length: 您可以添加额外的长度检查:

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

or you can simply do: 或者您可以简单地执行以下操作:

if ([sBarcodeValues hasPrefix:@"2C2C2P"]) {
}

This will work no matter how long sBarcodeValues is. 无论sBarcodeValues有多长,这都将起作用。

It is a good practice that you check the string length before substring. 最好在子字符串之前检查字符串长度。

You can check that as follows: 您可以检查如下:

if (sBarcodeValues.length>=6 && [[sBarcodeValues substringToIndex:6] isEqualToString:@"2C2C2P"]){

}

Edit: 编辑:

If you want use only substringToIndex then length check is necessary to prevent crash. 如果只想使用substringToIndex则必须进行长度检查以防止崩溃。

Otherwise, hasPrefix will do the work. 否则, hasPrefix将完成工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM