0

我在文本字段中有一些文本,它们以 6 个字符开头,我自己的输入也是 6 个字符长,我使用这段代码让它们成为比较的一部分:

unichar aChar1 = [mainTextController.text characterAtIndex:6];
    unichar aChar2 = [mainTextController.text characterAtIndex:7];
    unichar aChar3 = [mainTextController.text characterAtIndex:8];
    unichar aChar4 = [mainTextController.text characterAtIndex:9];
    unichar aChar5 = [mainTextController.text characterAtIndex:10];
    unichar aChar6 = [mainTextController.text characterAtIndex:11];

现在,当我这样做时,它会暂停我的模拟器,但是当我在 0、1、2、3、4、5 中转动 6、7、8、9、10、11 时,它确实可以工作。怎么会?

*由于未捕获的异常'NSRangeException'而终止应用程序,原因:'-[__NSCFString characterAtIndex:]:范围或索引超出范围')有人可以向我解释一下

4

2 回答 2

2

你是说你有一个包含起始值和输入的 12 个字符的字符串连接在一起吗?我强烈怀疑情况并非如此。

使用调试器,在问题的第一行打断并进入po [mainTextController text]调试控制台。你会发现字符串没有你期望的那么长。

于 2012-05-17T23:26:34.237 回答
0

您正在尝试访问超出 mainTextController.text 中文本字符串范围的字符

您应该在访问该字符之前检查字符串的长度:

if([mainTextController.text length] > 12)
{
    unichar aChar6 = [mainTextController.text characterAtIndex:11];
}
于 2012-05-17T23:25:04.237 回答