我有一个UITextView
带有格式的工具栏。在我按下“粗体”按钮后,它会更改文本/选择并将操作注册到文本视图的NSUndoManager
.
当您尝试撤消时,restoreText:
会一遍又一遍地调用,直到您杀死应用程序
一些示例代码:
- (void)bold {
NSRange range = self.textView.selectedRange;
NSRange oldRange = range;
NSString *oldText = self.textView.text;
NSString *selection = [self.textView.text substringWithRange:range];
self.textView.scrollEnabled = NO;
self.textView.text = [self.textView.text stringByReplacingCharactersInRange:range
withString:[NSString stringWithFormat:@"<b>%@</b>", selection]];
self.textView.scrollEnabled = YES;
if (range.length == 0) { // If nothing was selected
range.location += 3; // Place selection between tags
} else {
range.location += range.length + 7; // Place selection after tag
range.length = 0;
}
self.textView.selectedRange = range;
[[self.textView.undoManager prepareWithInvocationTarget:self] restoreText:oldText withRange:oldRange];
[self.textView.undoManager setActionName:@"bold"];
}
- (void)restoreText:(NSString *)text withRange:(NSRange)range {
NSLog(@"restoreText:%@ %@",text, [NSNumber numberWithBool:[self.textView.undoManager isUndoing]]);
NSString *oldText = self.textView.text;
NSRange oldRange = self.textView.selectedRange;
self.textView.scrollEnabled = NO;
self.textView.text = text;
self.textView.scrollEnabled = YES;
self.textView.selectedRange = range;
[[self.textView.undoManager prepareWithInvocationTarget:self] restoreText:oldText withRange:oldRange];
}
和控制台:
2012-10-04 18:10:14.207 undotest[8861:c07] restoreText: 1
2012-10-04 18:10:14.633 undotest[8861:c07] restoreText:<b></b> 0
2012-10-04 18:10:15.117 undotest[8861:c07] restoreText: 0
2012-10-04 18:10:15.589 undotest[8861:c07] restoreText:<b></b> 0
2012-10-04 18:10:16.017 undotest[8861:c07] restoreText: 0
2012-10-04 18:10:16.557 undotest[8861:c07] restoreText:<b></b> 0
我[self.textView.undoManager isUndoing]
在注册调用之前尝试过检查restoreText:withRange:
,但是崩溃了:
2012-10-04 18:10:49.297 undotest[8904:c07] restoreText: 1
2012-10-04 18:10:53.412 undotest[8904:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '_endUndoGroupRemovingIfEmpty:: WebThreadSafeUndoManager 0x76551e0 is in invalid state, endUndoGrouping called with no matching begin
'
此代码在 iOS5 上运行,但在 iOS6 上停止运行。我已经向 Apple 提交了一个错误,但我不确定我是否做错了什么