2016-10-26 7 views
0

Так что в моем представлении таблицы у меня есть массив, называемый dataArray, и он получает свои объекты с сервера с помощью JSON. Я добавил кнопку в каждую ячейку, и когда нажата кнопка, ячейка должна переместиться в другой раздел/или другой массив с именем followArray, чтобы быть более точным. Теперь ячейки передаются в другой раздел, но после перемещения 6 ячеек я получаю сообщение об ошибке. Все массивы - NSMutableArray. Кроме того, я новичок в iOS, поэтому стараюсь работать со мной, спасибо.Ошибка в представлении таблицы, когда ячейки переключают разделы

2016-10-26 17: 27: 19,569 CustomCellApp [3212: 198103] * Нагрузочный приложение из-за неперехваченного исключением 'NSRangeException', причина: «* - [__ NSArrayM objectAtIndex]: индекс 6 за пределы [0 .. 4]

---------------------

примечание стороны, я могу сделать отдельный пост об ошибке но у меня есть еще одна проблема: изображения, отображаемые в ячейках, меняются на другие изображения при переключении разделов, используя модуль SDWebImag е.

---------------------

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

if (!isFiltered) { 

    if (section == 0) { 
     return [followedArray count]; 
    } 
    else if (section == 1) { 
     return [dataArray count]; 
    } 
} 
return [filteredArray count]; 

} 

--------------- ------

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
if (section == 0) { 
    return @"Followed Data"; 
} 
else { 
    return @"All Data"; 
} 
} 

---------------------

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

static NSString *CellIdentifier = @"Cell"; 
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (!cell) { 
    cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 

// Configuring the cell 
Data * dataObject; 
if (!isFiltered) { 

    if (indexPath.section == 0) { 
     dataObject = [followedArray objectAtIndex:indexPath.row]; 
    } 
    else if (indexPath.section == 1) { 
     dataObject = [dataArray objectAtIndex:indexPath.row]; 
    } 
} 
else { 
    dataObject = [filteredArray objectAtIndex:indexPath.row]; 
} 

// Loading Images 
if (!isFiltered) { 
    // Exception Breakpoint Here 
    NSURL * imgURL = [[dataArray objectAtIndex:indexPath.row] valueForKey:@"dataURL"]; 
    [cell.myImageView setContentMode:UIViewContentModeScaleAspectFit]; 
    [cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"no-image.png"] options:SDWebImageRefreshCached]; 
}else{ 
    NSURL * imgURL = [[filteredArray objectAtIndex:indexPath.row] valueForKey:@"dataURL"]; 
    [cell.myImageView setContentMode:UIViewContentModeScaleAspectFit]; 
    [cell.myImageView sd_setImageWithURL:imgURL placeholderImage:[UIImage imageNamed:@"no-image.png"] options:SDWebImageRefreshCached]; 
} 

// Loading Follow Button 
cell.followButton.tag = indexPath.row; 
[cell.followButton addTarget:self action:@selector(followButtonClick:) forControlEvents:UIControlEventTouchUpInside]; 
cell.followButton.hidden = NO; 

return cell; 
} 

---------------------

-(void)followButtonClick:(UIButton *)sender { 

// Adding row to tag 
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.myTableView]; 
NSIndexPath *indexPath = [self.myTableView indexPathForRowAtPoint:buttonPosition]; 

// Creating an action per tag 
if (indexPath != nil) 
{ 

    // Change Follow to Following 
    [sender setImage:[UIImage imageNamed:@"follow.png"] forState:UIControlStateNormal]; 
    cell.followButton.hidden = YES; 
    cell.followedButton.hidden = NO; 


    // ----- ERROR BEGINS HERE ----- // 
    [self.myTableView beginUpdates]; 

    // ----- Inserting Cell to Section 0 ----- *CAUSING PROBLEMS* 
     // Exception Breakpoint Here 
    [followedArray addObject:[dataArray objectAtIndex:indexPath.row]]; 
    [myTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:followedArray.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 

    NSLog(@"indexPath.row = %ld", (long)indexPath.row); 

    // ----- Removing Cell from Section 1 ----- *WORKING* 
    [dataArray removeObjectAtIndex:indexPath.row]; 
    NSInteger rowToRemove = indexPath.row; 
    [self.myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObjects:[NSIndexPath indexPathForRow:rowToRemove inSection:1], nil] withRowAnimation:YES]; 

    NSLog(@"Array =%@",followedArray); 

    [self.myTableView endUpdates]; 
    // ----- ERROR ENDS HERE ----- // 
} 
} 

------------------ ---

+0

почему вы получаете позицию пользователя мыши, чтобы получить клетку, на самом деле клетки в Tableview повторно используются, так что если я нажал на номер ячейки 4, может быть, это будет та же позиция для ячейки номер 8, так что вы ожидаете от indexPath? Вы должны реализовать действие кнопки внутри ячейки и создать делегат, когда он нажал кнопку, чтобы получить правильный путь индекса –

+0

@AliOmari. Это может быть причиной ошибки? Что мне делать, чтобы исправить это? – BroSimple

+0

Возможно, это не причина, но вы делаете это неправильно. , поэтому давайте исправим это первым и перейдем к следующему шагу. Необходимо добавить действие кнопки внутри ячейки и передать контроллер представления в качестве делегата для этой ячейки, чтобы вы могли вызвать контроллер вида при нажатии кнопки. –

ответ

0

Это то, что помогло мне исправить ошибки, которые у меня были. Кредиты @AliOmari за помощь мне.

В cellForRowAtIndexPath

// Configuring the cell 
Data * dataObject; 
if (!isFiltered) { 

    if (indexPath.section == 0) { 
     dataObject = [followedArray objectAtIndex:indexPath.row]; 
     [cell populateCell:dataObject isFollowed:YES indexPath:indexPath parentView:self]; 
    } 
    else if (indexPath.section == 1) { 
     dataObject = [dataArray objectAtIndex:indexPath.row]; 
     [cell populateCell:dataObject isFollowed:NO indexPath:indexPath parentView:self]; 
    } 
} 
else { 
    dataObject = [filteredArray objectAtIndex:indexPath.row]; 
    [cell populateCell:dataObject isFollowed:NO indexPath:indexPath parentView:self]; 
} 
return cell; 

Внутри моей кнопки

[self.myTableView beginUpdates]; 

    // ----- Inserting Cell to Section 0 ----- 
    [followedArray insertObject:[dataArray objectAtIndex:indexPath.row] atIndex:0]; 
    [myTableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade]; 
    //NSLog(@"indexPath.row = %ld", (long)indexPath.row); 

    // ----- Removing Cell from Section 1 ----- 
    [dataArray removeObjectAtIndex:indexPath.row]; 
    NSInteger rowToRemove = indexPath.row; 
    [self.myTableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObjects:[NSIndexPath indexPathForRow:rowToRemove inSection:1], nil] withRowAnimation:YES]; 
    //NSLog(@"Array =%@",followedArray); 

    [self.myTableView endUpdates];