设置UITextView的文本会导致崩溃
  我试图设置UITextView的文本,其中有一些非法字符,如“Unicode字符”OBJECT REPLACEMENT CHARACTER'(U + FFFC)“。 
  基本上,我有一个UITextView 。  现在用户点击它并键盘出现。  现在我用键盘上的文字(也被称为听写)。  当听写正在处理中(此时UITextView具有与默认占位符动画相对应的特殊字符),我尝试使用以下设置来设置文本视图的值: 
textView.text = @""
这会导致以下崩溃:
 *** Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
我从crashlytics那里得到的堆栈跟踪:
0    CoreFoundation     __exceptionPreprocess + 130
2    CoreFoundation     -[NSException initWithCoder:]
3    CoreFoundation     mutateError + 222
4    Foundation     -[NSString stringByReplacingCharactersInRange:withString:] + 134
5    UIKit      __37-[UITextInputController textInRange:]_block_invoke + 310
6    UIFoundation       -[NSTextStorage coordinateReading:] + 36
7    UIKit      -[UITextInputController textInRange:] + 232
8    UIKit      -[TIDocumentState(UITextInputAdditions) _contextAfterPosition:inDocument:] + 190
9    UIKit      -[TIDocumentState(UITextInputAdditions) initWithDocument:] + 150
10    UIKit     +[TIDocumentState(UITextInputAdditions) documentStateOfDocument:] + 52
11    UIKit     -[UIKeyboardImpl updateForChangedSelectionWithExecutionContext:] + 288
12    UIKit     -[UIKeyboardTaskQueue continueExecutionOnMainThread] + 352
13    UIKit     -[UIKeyboardTaskQueue performTask:] + 248
14    UIKit     -[UIKeyboardImpl updateForChangedSelection] + 96
15    UIKit     -[UIKeyboardImpl selectionDidChange:] + 102
16    UIFoundation      -[NSTextStorage coordinateReading:] + 36
17    UIKit     -[UITextInputController _coordinateSelectionChange:] + 100
18    UIKit     -[UITextInputController _setSelectedTextRange:] + 604
19    UIKit     -[UITextView setAttributedText:] + 392
20    UIKit     -[UITextView setText:] + 134
我还创建了一个演示此问题的示例项目。 您可以从以下网址获取该项目:https://dl.dropboxusercontent.com/u/80141854/TextViewDictationCheck.zip
异常可以通过以下步骤重现:
  我发现了一种避免这种崩溃的方法:在设置UITextView的文本时,我们可以使用以下代码: 
  我还发现了一个解决方法,可以在重置UITextView上的文本时使用它: 
[self.textView setSelectedRange:NSMakeRange(0, [[self.textView textStorage] length])];
[self.textView insertText:@""];
[self.textView setText:@""];
但是,如果我们只使用setText:来设置文本,我仍然不明白为什么会发生这种崩溃。
基金会代码发生异常,而不是您的代码。 如果字符串在听写正在处理时发生改变,则会导致此崩溃。 当您触摸麦克风按钮时,它会将一个占位符放入字符串中,然后在完成处理时用文本替换它。 如果您更改字符串并删除占位符,则会导致崩溃。
  解决方法是确保在口述正在处理时不改变字符串。  您可以通过检查当前输入模式的主要语言来做到这一点。  当听写正在进行时,它被设定为dictation : 
- (IBAction)sendPressed:(id)sender
{
    NSString *primaryLanguage = [self.textView textInputMode].primaryLanguage;
    if(![primaryLanguage isEqualToString:@"dictation"])
    {
        // Your original method body:
        NSString *textViewText = self.textView.text;
        textViewText = @"";
        self.textView.text = nil;
        self.textView.text = @"";
    }
}
如果听写正在进行,则跳过代码以清空文本视图。
链接地址: http://www.djcxy.com/p/20439.html