This question already has an answer here:
“[NSBigMutableString substringWithRange:]: Range {0, 10} out of bounds; string length 9” error with Undo
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
今天,我在isEqualToString的text属性为UISearchBar的方法上收到了随机崩溃。该崩溃报告于Crashlytics。

以下是代码段。

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if( [searchBar.text isEqualToString:@" "] )
    {
        [searchBar setText:@""];
    }
    if ( searchBar.text.length >= 2 )
    {
        [self performSelectorInBackground:@selector(searchForKeyword:) withObject:searchBar.text];
    }
}

-(void)searchForKeyword:(NSString *)keyword
{
    if ([keyword isEqualToString:searchBar.text])
    {
        //Search for keyword
    }
}


坠机说

Fatal Exception: `NSRangeException`
*** -[NSBigMutableString _newBigSubstringWithRange:wantsMutable:zone:]: Range {0, 4} out of bounds; string length 3


我已经尝试调试导致崩溃的代码行,但没有成功。它只是随机崩溃。
提前致谢

最佳答案

该错误是由于以下原因引起的:您将搜索栏文本设置为

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText


您应该使用下面的方法代替您使用的方法。

- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text NS_AVAILABLE_IOS(3_0); // called before text changes

关于ios - isEqualToString:给出超出范围的异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38179125/

10-11 23:01