2015-06-20 4 views
0

Я реализовал панель поиска (и контроллер отображения) в uitableview, используя приведенный ниже код. Когда я печатаю текстовое поле поиска, я получаю следующую ошибку sigabrt:UitableView Search Text Sigbart Error - ios

Завершение приложения из-за неотображенного исключения «NSUnknownKeyException», причина: '[valueForUndefinedKey:]: этот класс не является ключевым значением, совместимым с кодировкой для имени ключа «.

Я пересматривал учебное пособие, которое я выполнял, и четырехкратно проверял код, однако я не могу найти причину ошибки, может ли кто-нибудь помочь?

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     return [self.searchResults count]; 
    } else { 
     return _restaurantsInCity.count; 
    } 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"RestaurantCell"; 
    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 

    RestarauntEntity *currentRestaurant = nil; 
    if (tableView == self.searchDisplayController.searchResultsTableView) { 
     currentRestaurant = [[self.searchResults objectAtIndex:indexPath.row]]; 
    } else { 
     currentRestaurant = [self.restaurantsInCity objectAtIndex:indexPath.row]; 
    } 

    NSString *decodedText1 = [currentRestaurant.title stringByReplacingOccurrencesOfString:@"’" withString:@"'"]; 
    NSString *decodedText = [decodedText1 stringByReplacingOccurrencesOfString:@"&" withString:@"&"]; 
    cell.textLabel.text = decodedText; 
    cell.textLabel.font = [UIFont fontWithName:@"avenir" size:16.0f]; 
    cell.textLabel.textColor=[UIColor blackColor]; 
    cell.detailTextLabel.text = currentRestaurant.city; 
    cell.detailTextLabel.font = [UIFont fontWithName:@"avenir" size:12.0f]; 
    cell.detailTextLabel.textColor=[UIColor darkGrayColor]; 

    return cell; 
} 

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope 
{ 
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"name contains[cd] %@", searchText]; 
    searchResults = [_restaurantsInCity filteredArrayUsingPredicate:resultPredicate]; 
} 

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 
{ 
    [self filterContentForSearchText:searchString 
           scope:[[self.searchDisplayController.searchBar scopeButtonTitles] 
             objectAtIndex:[self.searchDisplayController.searchBar 
                selectedScopeButtonIndex]]]; 

    return YES; 
} 
+0

Попытка создавая контрольную точку исключения, а также позволяя объектам-зомби объектив-c получить лучшую картину при сбое. –

ответ

0

Попробуйте

Это происходит, если вы создали какой-либо выход или действие на кнопку, которая does't существует больше. Проверьте все ваши действия и выходы. Перейдите на свою раскадровку и щелкните правой кнопкой мыши на желтом знаке вашего монитора управления и удалите все действия и выходы с желтым знаком.

enter image description here

Надеется, что это помогает.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Попробуйте этот ответ надеюсь, что это помогает.

+0

Спасибо, но я уже пробовал, что на каких-либо из моих контроллеров просмотра нет действий или выходов, у которых есть желтый флаг. Любые другие предложения, я потратил часы на поиск решения, насколько я знаю, что мой код хорош, есть ли что-нибудь еще? – user1419810

+0

Спасибо, я посмотрел, но не знаю, как проверить «висячие соединения». Снимок экрана в ответе не показывает никаких связей с «!». восклицательные знаки, где я их нахожу? – user1419810

0

Если вы не можете отлаживать свой текущий код, вы можете реализовать функциональность панели поиска с помощью UITextField тоже, что я сделал. Просто поместите UITextField вместо строки поиска, над вашим UITableView и установите делегат. Убедитесь, что вы используете правильное имя переменных вашего класса объектов данных. Я пишу свой код здесь, дайте мне знать, если это помогает

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

if (isFromSearchResult) // BOOL to determine is from search result or not 
{ 
    return [searchResults count]; 
} 
else 
{ 
    return myAppDelegate.offersArr.count; 
} 

}

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

customCell = (offersCustomTableViewCell*)[tableView dequeueReusableCellWithIdentifier:@"Cell"]; 

if(isFromSearchResult) 
{ 
    dataObj = [searchResults objectAtIndex:indexPath.row]; //dataObj is object of NSObject data class 
} else 
{ 
    dataObj = [myAppDelegate.offersArr objectAtIndex:indexPath.row]; 
} 

customCell.LblOffer.text = [dataObj.OfferTitle uppercaseString]; 

NSString *validity = @"VALID TILL: "; // dataObj.ValidTime; 
customCell.LblValid.text = [validity stringByAppendingString:dataObj.ValidTime]; 

return customCell; 

}

- (недействительными) filterContentForSearchText: (NSString *) SearchText объем: (NSString *) сфера { // здесь в поисках трех Поля- название, содержание и объявления платье

NSPredicate *predicateOfferTitle = [NSPredicate predicateWithFormat:@"OfferTitle contains[cd] %@", searchText]; 
NSPredicate *predicateOfferContent = [NSPredicate predicateWithFormat:@"OfferContent contains[cd] %@", searchText]; 
NSPredicate *predicateAddress = [NSPredicate predicateWithFormat:@"Address contains[cd] %@", searchText]; 

NSArray *subPredicates = [NSArray arrayWithObjects:predicateOfferTitle, predicateOfferContent,predicateAddress, nil]; 
NSPredicate *orPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:subPredicates]; 
searchResults = [myAppDelegate.offersArr filteredArrayUsingPredicate:orPredicate]; 
//NSLog(@"%@", searchResults); 

}

- (BOOL) TextField: (UITextField *) TextField shouldChangeCharactersInRange: (NSRange) Диапазон replacementString: (NSString *) строка {

NSString *value = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
//NSLog(@"value: %@", value); 
if (![value isEqualToString:@""]) { 
    [self filterContentForSearchText:value scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; 

    isFromSearchResult=YES; 
} 
else 
{ 
    isFromSearchResult=NO; 
} 

[offersTable reloadData]; 
return true; 

}

+0

Спасибо, я только что попробовал это, но без радости, авария все еще случается. Это так расстраивает, что это невероятно! – user1419810