2012-11-20 24 views
0

我試着瞭解從一些教程發生了什麼,但不幸的是我沒有找到答案。 我認爲這個問題可能是我沒有IF萬一我在搜索結果中爲零。UIsearchBar顯示結果,但當我按下的東西,沒有存在的應用程序粉碎

錯誤是: 'NSRangeException',原因: '* - [__ NSArrayM objectAtIndex:]:索引0超出界限爲空數組'

我使用的方法:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 
{ 
    //removes previos search result 
    [[self searchResults]removeAllObjects]; 

    for (Books *book in [self.fetchResultsController fetchedObjects]) 
    { 
      if([self searchResults] != nil) 
      { 
       NSComparisonResult result = [book.title compare:searchText 
                options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) 
                range:NSMakeRange(0, [searchText length])]; 
       if (result == NSOrderedSame) 
       { 
         [self.searchResults addObject:book]; 
       } 
      } 
     } 
} 

還可以在GIT中找到我的全部項目: https://github.com/dennis87/git_bookList

編輯: 當我嘗試把這個像這樣

if([scope isEqualToString:@「All」] || [book.title isEqualToString:範圍])

應用美眉沒有讓我按任何東西..

回答

0

問題是numberOfSectionsInTableView對於搜索結果表總是返回1,即使沒有搜索結果。崩潰發生在titleForHeaderInSection

return [[[self searchResults] objectAtIndex:section] author]; 

因爲索引爲0的對象是從一個空數組訪問的。

因此,如果搜索結果數組爲空,或者您將titleForHeaderInSection更改爲返回不同於搜索結果表的內容,則要麼更改numberOfSectionsInTableView以返回0。 。

+0

謝謝:)在numberOfSectionsInTableView 我試試這個: 如果([個體經營SearchResult所]) 返回1; else return 0; 在titleForHeaderInSection我試試這個: 如果((的tableView == [自searchDisplayController] searchResultsTableView])&& [個體經營SearchResult所]) 但它不工作。我如何檢查數組是否爲空?如你所知,我是obj c的新手。 – Dennis

+0

@ Dennis:使用if([[self searchResults] count] == 0)'來檢查數組是否爲空。 –

+0

感謝它的工作:) – Dennis

0

您可能要檢查,如果數組包含從中刪除所有對象之前的對象..

if(dataSourceArray){ //use your datasource array instead 
    [[self searchResults]removeAllObjects]; 
} 
+0

它並沒有幫助:(未解決的問題再次 – Dennis

相關問題