經過一些修補後,我想我已經弄明白了。喬希,我用你的建議開始。我不確定你是否編輯了你的建議或者只是刪除了它,但沒有了,所以我不能在我的答案中引用它。
無論如何,在每次調用replaceCharactersInRange:withString:
之後,您必須改變要替換的範圍,否則在範圍不匹配時會發生不好的事情。以下是我結束了:
// array of NSValue objects storing an NSRange
NSArray *replaceRanges = [self replaceRanges];
NSString *replaceString = [self replaceString];
// array of NSString objects you are going to use for the replace operation, just replaceString repeated [replaceRanges count] times
NSArray *replaceStrings = [self replaceStrings];
NSTextView *textView = [self textView];
// the amount we have to shift subequent replace ranges after each call to replaceCharactersInRange:withString:
NSInteger locationShift = 0;
// check to makes sure the replace can occur
if ([textView shouldChangeTextInRanges:replaceRanges replacementStrings:replaceStrings]) {
// we want to treat all these replacements as a single replacement for undo purposes
[[textView textStorage] beginEditing];
for (NSValue *rangeValue in replaceRanges) {
NSRange range = [rangeValue rangeValue];
// replace the range shifted by locationShift with our replaceString
[[textView textStorage] replaceCharactersInRange:NSMakeRange(range.location + locationShift, range.length) withString:replaceString];
// update the shift amount, which is the difference between our replaced string length and the original match length
locationShift += [replaceString length] - range.length;
}
// end the grouping operation
[[textView textStorage] endEditing];
}
這個偉大的工程和支持撤消預期,撤消所有替代而復一次這種操作的結果。
無論如何感謝喬希,因爲他的回答讓我指出了正確的方向。
我把它刪除了,因爲我沒有嘗試過;那麼當我嘗試編譯/運行它時,我無法讓它做任何有用的事情。很高興它是有幫助的!爲了後代的緣故,我已經放棄了它。 – 2011-04-07 03:47:04
偉大的問題,BTW,和很好的解決方案! – 2011-04-07 03:49:47