0

tableviewfetchedresultscontrollersearchbar으로 채워져 있습니다. 지금까지 애플 리케이션을 만드는 동안 나는 단지 7 개의 셀을 사용했고 위대한 일을했지만, 7 개 이상의 셀을 사용하기 시작한 이후 검색 바를 만질 때 빈 배열을 벗어난 오류가 발생합니다. 하지만 7 개의 셀로 되돌려 놓으면 완벽하게 작동합니다.Tableview에서 빈 배열의 인덱스를 벗어남

무엇이 잘못되었을 수 있습니까?

오류 : 때문에, 이유 캐치되지 않는 예외 'NSRangeException'에 응용 프로그램을 erminating : '*-[__NSArrayM objectAtIndex:]: 인덱스 2를 경계를 넘어 하늘의 배열을위한'당신이 충돌을 볼 수 있습니까

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    self.title = @"Exercises"; 



    id appDelegate = [[UIApplication sharedApplication] delegate]; 
    _managedObjectContext = [appDelegate managedObjectContext]; 

    NSError *error; 
    if (![[self fetchedResultsController] performFetch:&error]) { 
     NSLog(@"%@ %@", error, [error userInfo]); 
     abort(); 
    } 

    _searchResults = [[NSMutableArray alloc] init]; 


} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 

    NSIndexPath *selectedIndexPath = [_tableView indexPathForSelectedRow]; 
    if (!selectedIndexPath) { 
     [_tableView setContentOffset:CGPointMake(0, 44) animated:NO]; 
    } 
    else { 
     [_tableView deselectRowAtIndexPath:selectedIndexPath animated:YES]; 
    } 
} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
    if (self.searchDisplayController.isActive) { 
     [self.searchDisplayController setActive:NO animated:YES]; 
    } 
} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

#pragma mark - UITableViewDataSource 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    if (self.searchDisplayController.isActive) { 
     return 1; 
    } 
    return [[_fetchedResultsController sections] count]; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    if (self.searchDisplayController.isActive) { 
     return nil; 
    } 
    return [[[_fetchedResultsController sections] objectAtIndex:section] name]; 
} 

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 22)]; 
    view.backgroundColor = [UIColor colorWithRed:20.0/255.0 green:20.0/255.0 blue:20.0/255.0 alpha:0.8]; 

    UILabel *sectionLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 160, 22)]; 
    sectionLabel.font = [UIFont fontWithName:@"Avenir-Book" size:16.0f]; 
    sectionLabel.text = @"Search Results"; 

    if (!self.searchDisplayController.isActive) { 
     sectionLabel.text = [[[_fetchedResultsController sections] objectAtIndex:section] name]; 
    } 

    sectionLabel.backgroundColor = [UIColor clearColor]; 
    sectionLabel.textColor = [UIColor whiteColor]; 
    [view addSubview:sectionLabel]; 
    return view; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    if (self.searchDisplayController.isActive) { 
     return [_searchResults count]; 
    } 
    return [[[_fetchedResultsController sections] objectAtIndex:section] numberOfObjects]; 
} 

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

    if (!cell) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; 
     [self stampCell:cell atIndexPath:indexPath]; 
    } 

    [self configureCell:cell atIndexPath:indexPath]; 

    return cell; 
} 


#pragma mark - Cell 

- (void)stampCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
{ 
    if ([cell.reuseIdentifier isEqualToString:@"exerciseCell"]) { 

     UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 2, 150, 22)]; 
     textLabel.tag = kExerciseCellTextLabel; 
     textLabel.font = [UIFont systemFontOfSize:18.0]; 
     textLabel.textColor = [UIColor blackColor]; 
     textLabel.highlightedTextColor = [UIColor whiteColor]; 
     textLabel.backgroundColor = [UIColor clearColor]; 
     [cell.contentView addSubview:textLabel]; 

     UILabel *detailTextLabel = [[UILabel alloc] initWithFrame:CGRectMake(70, 24, 150, 18)]; 
     detailTextLabel.tag = kExerciseCellDetailTextLabel; 
     detailTextLabel.font = [UIFont systemFontOfSize:14.0]; 
     detailTextLabel.textColor = [UIColor colorWithRed:128.0/255.0 green:128.0/255.0 blue:128.0/255.0 alpha:1.0]; 
     detailTextLabel.highlightedTextColor = [UIColor colorWithRed:127.0/255.0 green:127.0/255.0 blue:127.0/255.0 alpha:1.0]; 
     detailTextLabel.backgroundColor = [UIColor clearColor]; 
     [cell.contentView addSubview:detailTextLabel]; 

    } 
} 

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath 
{ 
    if ([cell.reuseIdentifier isEqualToString:@"exerciseCell"]) { 

     UILabel *textLabel = (UILabel *)[cell.contentView viewWithTag:kExerciseCellTextLabel]; 
     UILabel *detailTextLabel = (UILabel *)[cell.contentView viewWithTag:kExerciseCellDetailTextLabel]; 

     Exercise *exercise; 

     if (self.searchDisplayController.isActive) { 
      exercise = [_searchResults objectAtIndex:indexPath.row]; 
     } 
     else { 
      exercise = [_fetchedResultsController objectAtIndexPath:indexPath]; 
     } 

     textLabel.text = [exercise valueForKey:kExerciseName]; 
     detailTextLabel.text = [NSString stringWithFormat:@"%@ - %@", [[exercise valueForKey:kExerciseEType] valueForKey:kExerciseTypeName], [[exercise valueForKey:kExerciseGear] valueForKey:kGearName]]; 

     cell.selectionStyle = UITableViewCellSelectionStyleGray; 
     cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 

    } 
} 


#pragma mark - UITableViewDelegate 

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [self performSegueWithIdentifier:@"exerciseDetail" sender:self]; 
} 

#pragma mark - UISearchBarDelegate 

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 
{ 
    [_searchResults removeAllObjects]; 
    if (searchString.length > 0) { 

     for (Exercise *exercise in [_fetchedResultsController fetchedObjects]) { 
      NSRange range = [[exercise valueForKey:kExerciseName] rangeOfString:searchString options:NSCaseInsensitiveSearch]; 
      if (range.location == 0) { 
       [_searchResults addObject:exercise]; 
      } 
     } 
    } 
    return YES; 
} 

- (BOOL)searchBarShouldBeginEditing:(UISearchBar*)searchBar { 
    [super setPan]; 
    return YES; 
} 

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar 
{ 
    [super setPan]; 
    return YES; 
} 

#pragma mark - NSFetchedResultsControllerDelegate 

- (NSFetchedResultsController *)fetchedResultsController 
{ 
    if (_fetchedResultsController) { 
     return _fetchedResultsController; 
    } 

    NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:kExercise inManagedObjectContext:_managedObjectContext]; 
    [request setEntity:entity]; 

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:kExerciseName ascending:YES]; 
    [request setSortDescriptors:[NSArray arrayWithObject:sort]]; 

    NSFetchedResultsController *fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:_managedObjectContext sectionNameKeyPath:kExerciseFirstLetter cacheName:@"ExerciseList"]; 
    [self setFetchedResultsController:fetchedResultsController]; 
    [_fetchedResultsController setDelegate:self]; 

    return _fetchedResultsController; 
} 

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller 
{ 
    [self.tableView beginUpdates]; 
} 

- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo 
      atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type 
{ 
    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject 
     atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type 
     newIndexPath:(NSIndexPath *)newIndexPath 
{ 
    UITableView *tableView = self.tableView; 

    switch(type) { 
     case NSFetchedResultsChangeInsert: 
      [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeDelete: 
      [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 

     case NSFetchedResultsChangeUpdate: 
      [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath]; 
      break; 

     case NSFetchedResultsChangeMove: 
      [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      [tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
      break; 
    } 
} 

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller 
{ 
    [self.tableView endUpdates]; 
} 

@end 
+0

검색된 바를 터치 할 때 발생하는 오류를 추가했습니다 –

답변

1

그것은 보여줍니다. 내가 더 당신을 도울 수있는 문제가 know..so 나를 보자 solved..please하지 않으면 그렇게함으로써

..

+0

이 링크를 확인하십시오. 도움이 될만한 정보가 있습니다 .http : //stackoverflow.com/questions/4965827/terminating-app-due-to-uncaught-exception-on-ios – Shivaay

+0

nslog? 또는 관련이없는 위치입니다. –

+0

어레이에서 패스트가 nil이지만 nil이 아닌 패칭 된 객체가 있는지 확인하기 위해 뷰의 빠른 열거 형을 가져 왔는지 확인하십시오. 그게 당신이 의미 한 것입니까? –

0

- 표시 할 때 바로 검색 결과 또는 전체 목록을 표시 할 때?

단지 검색 결과 인 경우 _searchResults에는 7 개가 넘는 레코드가 없습니다.

모든 결과를 표시 할 경우 _fetchedResultsController.sections의 각 값에서 레코드 수를 확인하십시오. 7 개 이상의 레코드가없는 것처럼 보입니다. 배열의 일부가 배열 요소 후에는

저것 집어 넣어 NSLog 문을 확인하고 it..IT가 비어있는 배열을 보여줍니다 실행 empty..the 더 좋은 방법을 여전히 같은

+0

8 개 이상의 셀이 있고 충돌하는 검색 창을 터치하면 searchdisplaycontroller가 표시되지 않습니다. searchResults를 사용하여 아무 것도 할 필요가 없으며 검색 창을 터치 할 때 uitableviewdatasource를 호출하지도 않습니다. –

0

안녕 내가 생각 하시다면 _searchResults에서 모든 요소를 ​​제거하는 것은이 때문일 수 있습니다 응용 프로그램이 충돌합니다. 한 번 확인해보십시오.

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString 
{ 
    [_searchResults removeAllObjects]; 
+0

그 라인을 제거해야합니까? –

관련 문제