【问题标题】:charachterAtIndex max range?charachterAtIndex 最大范围?
【发布时间】:2012-05-17 23:21:38
【问题描述】:

我在文本字段中有一些文本,它们以 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:]: Range or index out of bounds') 谁能给我解释一下

【问题讨论】:

    标签: iphone objective-c xcode


    【解决方案1】:

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

    使用调试器,在问题的第一行打断,然后在调试控制台中转到po [mainTextController text]。你会发现字符串没有你想象的那么长。

    【讨论】:

    • 太棒了,你们两个真的让我想到了这一点,所以我添加了一点延迟,所以我会确保我自己的输入字符在我的代码试图让它们分隔符时出现在哪里,并且有效!谢谢我做到了:dispatch_after(dispatch_time(DISPATCH_TIME_NOW,0.1* NSEC_PER_SEC),dispatch_get_current_queue(),^{
    • 我不明白您为什么需要延迟。您正在响应什么事件?
    【解决方案2】:

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

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

    if([mainTextController.text length] > 12)
    {
        unichar aChar6 = [mainTextController.text characterAtIndex:11];
    }
    

    【讨论】:

    • 太棒了,你们两个真的让我想到了这一点,所以我添加了一点延迟,所以我会确保我自己的输入字符在我的代码试图获取它们的分隔符时在那里,并且有效!谢谢我做到了:dispatch_after(dispatch_time(DISPATCH_TIME_NOW,0.1* NSEC_PER_SEC),dispatch_get_current_queue(),^{
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    相关资源
    最近更新 更多