0

我想添加一個searchBarController到我的tableView中。當我構建應用程序時,我沒有收到任何錯誤,但是當我開始在searchBar中輸入內容時,該應用程序會引發異常並崩潰。SearchBarController謂詞導致崩潰

導致崩潰的行在最後一段代碼中註釋如下。有人知道這裏可能會出現什麼問題嗎?非常感謝!

我.h文件中的有關部分:

@interface BusinessesViewController : UITableViewController<CLLocationManagerDelegate, 
UISearchDisplayDelegate> { 

    IBOutlet UITableView *mainTableView; 
    NSArray *businesses; 
    NSMutableData *data; 
    NSArray *filteredBusinesses; 
} 

我的viewDidLoad方法的主要部分:

- (void)viewDidLoad { 
    filteredBusinesses = [[NSArray alloc]init]; 
} 

NumberOfRowsInSection方法:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: 
(NSInteger)section { 

    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return [filteredBusinesses count]; 
    } 
    else { 
     return [businesses count]; 
    } 
} 

的cellForRowAtIndexPath方法:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: 
(NSIndexPath *)indexPath { 

    BusinessesTableViewCell *cell = (BusinessesTableViewCell *)[tableView 
    dequeueReusableCellWithIdentifier:@"MainCell"]; 

    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     [cell.businessMainLabel setText:[[filteredBusinesses 
     objectAtIndex:indexPath.row]objectForKey:@"name"]]; 
    } 
    else { 
     [cell.businessMainLabel setText:[[businesses 
     objectAtIndex:indexPath.row]objectForKey:@"name"]]; 
    } 

    return cell; 
} 

謂詞和SearchDisplayController方法:

- (void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope { 

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"beginswith[cd] %@", 
    searchText]; 

    //THIS LINE OF CODE CAUSES THE CRASH 
    filteredBusinesses = [businesses filteredArrayUsingPredicate:predicate]; 
} 

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller 
    shouldReloadTableForSearchString:(NSString *)searchString { 

    [self filterContentForSearchText:searchString scope: 
    [[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex: 
    [self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; 
    return YES; 
} 

回答

1

你的謂語是錯誤的,關鍵丟失。從其他代碼,它看起來好像 在businesses的對象有一個「名稱」屬性,所以謂語應該

[NSPredicate predicateWithFormat:@"name BEGINSWITH[cd] %@", searchText] 
            ^key ^operator ^value 
+0

感謝馬丁,我覺得我越來越接近這裏。 name屬性來自JSON響應,如下所示:'[[business objectAtIndex:indexPath.row] valueForKey:@「name」]'關於如何處理這個問題的任何想法? – Brandon 2014-08-28 08:49:49

+0

@Brandon:然後上面的工作。 - 請注意,'valueForKey:'通常是錯誤的方法(它是用於鍵值編碼的),上面的代碼使用'objectForKey:'這是正確的。 – 2014-08-28 08:53:32

+0

好的,謝謝,如果我輸入一個確實在tableView中的字母,它現在只會崩潰。如果我輸入的東西不在tableView數組中,它會適當地說「沒有結果」,爲什麼這個問題仍然會崩潰? – Brandon 2014-08-28 08:57:40