1

我已经搜索了帮助,但在这里找不到。我有一个检查拼写的按钮,然后用猜测替换单词。我在按钮中有以下代码:

UITextChecker *checker = [[UITextChecker alloc] init];
NSRange checkRange = NSMakeRange(0, [input length]);
NSRange misspelledRange = [checker rangeOfMisspelledWordInString:input
                                                           range:checkRange
                                                      startingAt:checkRange.location
                                                            wrap:NO
                                                        language:@"en_US"];

NSArray *arrGuessed = [checker guessesForWordRange:misspelledRange inString:input language:@"en_US"];
if (misspelledRange.location != NSNotFound) {
    input = [input stringByReplacingCharactersInRange:misspelledRange
                                           withString:[arrGuessed objectAtIndex:0]];
}

它确实修复了一些单词,但不是全部。如果它找到一个单词,它无法猜测它会崩溃并关闭应用程序。我该如何解决这个问题?如果它无法猜出单词,我希望它忽略该过程。iOS 文档和 API 参考说如果找不到,它将返回一个空数组,但为什么它会崩溃?

这是错误:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
4

1 回答 1

0

你必须检查至少有一个猜测。这就是它崩溃的原因,你试图索引一个空数组:

NSArray *arrGuessed = [checker guessesForWordRange:misspelledRange inString:input language:@"en_US"];
// Check if we have a misspelled range and any guesses
if ([arrGuessed count] > 0 && misspelledRange.location != NSNotFound) {
    input = [input stringByReplacingCharactersInRange:misspelledRange withString:arrGuessed[0]];
}
于 2014-11-02T18:42:18.740 回答