2013-07-04 2 views
0

im получение ошибки: * Завершение приложения из-за неперехваченного исключения «NSInternalInconsistencyException», причина: «попытка вставить строку 0 в раздел 0, но в разделе 0 после этого есть только 0 строк обновление '*с ошибкой с пользовательскими флажками в ячейках uitableview

У меня есть 2 раздела, и я пытаюсь это сделать, когда вы нажимаете флажок ячейки в одном из разделов, он переходит в другой раздел (например: раздел 1-> раздел 2)

здесь некоторые соответствующий код шахты:

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
    if (!cell) 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
    if([indexPath section] == 0){ 
    cell.textLabel.text = [[[taskArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 
    cell.imageView.image = [UIImage imageNamed:@"checkboxtry2.png"]; 
    } else if ([indexPath section] == 1) { 
    cell.textLabel.text = [[[completedArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 
    cell.imageView.image = [UIImage imageNamed:@"checkboxtry2selected.png"]; 
    } 

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handlechecking:)]; 
    [cell.imageView addGestureRecognizer:tap]; 
    cell.imageView.userInteractionEnabled = YES; 
    return cell; 
} 
-(void)handlechecking:(UITapGestureRecognizer *)t{ 
     CGPoint tapLocation = [t locationInView:self.tableView]; 
     NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation]; 

     if (tappedIndexPath.section == 0) { 
      [completedArray addObject:[taskArray objectAtIndex:tappedIndexPath.row]]; 
      [taskArray removeObject:[taskArray objectAtIndex:tappedIndexPath.row]]; 
     } 
     else { 
      [taskArray addObject:[completedArray objectAtIndex:tappedIndexPath.row]]; 
      [completedArray removeObject:[completedArray objectAtIndex:tappedIndexPath.row]]; 
     } 
     [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:tappedIndexPath] withRowAnimation: UITableViewRowAnimationFade]; 
} 

У меня есть два массива: taskArray который обрабатывает объекты в разделе 0 и completedArray, который обрабатывает объекты в разделе 1.

--- EDIT --- Вот что я сейчас: TableViewController.h

@interface ToDoTableViewController : UITableViewController <Properties2ViewControllerDelegate, UITableViewDelegate, SettingsViewControllerDelegate> 
@property (strong, nonatomic) NSMutableArray *taskArray; 
@property (strong, nonatomic) NSMutableArray *completedArray; 
@property (strong, nonatomic) NSMutableArray *holdViewsArray; 
-(IBAction)addCell:(id)sender; 
-(void)buttonPressed:(id)sender; 
-(void)handlechecking:(UITapGestureRecognizer *)t; 

TableViewController.m

-(void) viewDidLoad{ 
    [self.tableView setDelegate:self]; 
    [self setModalTransitionStyle:UIModalTransitionStyleCrossDissolve]; 

    taskArray = [[NSMutableArray alloc] init]; 
    completedArray = [[NSMutableArray alloc]init]; 
    holdViewsArray = [[NSMutableArray alloc]init]; 
    } 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
    if (!cell) 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
    NSString *detailText = [NSString stringWithFormat:@"%.0f", [[taskArray objectAtIndex:[indexPath row]] timeInterval]]; 
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]; 
    [cell setBackgroundColor:[UIColor colorWithRed:236.0/255 green:240.0/255 blue:241.0/255 alpha:1.0f]]; 
    cell.textLabel.textColor = baseColor; 
    [[cell detailTextLabel] setText:detailText]; 
    [[cell detailTextLabel] setFont:[UIFont fontWithName:@"Avenir-Black" size:12]]; 
    [[cell textLabel] setFont:[UIFont fontWithName:@"AvenirNext-DemiBold" size:16]]; 

    if([indexPath section] == 0){ 
    cell.textLabel.text = [[[taskArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 
    cell.imageView.image = [UIImage imageNamed:@"unchecked.png"]; 
    } else if ([indexPath section] == 1) { 
    cell.textLabel.text = [[[completedArray objectAtIndex:[indexPath row]] taskName] uppercaseString]; 
    cell.imageView.image = [UIImage imageNamed:@"checked.png"]; 
    } 

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handlechecking:)]; 
    [cell.imageView addGestureRecognizer:tap]; 
    cell.imageView.userInteractionEnabled = YES; 
    return cell; 

} 
-(void)handlechecking:(UITapGestureRecognizer *)t{ 

     CGPoint tapLocation = [t locationInView:self.tableView]; 
     NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation]; 
     NSIndexPath *newIndexPath = nil; 

     if (tappedIndexPath.section == 0) { 

      NSUInteger newRowIndex = self.completedArray.count; 
      [self.completedArray addObject:[self.taskArray objectAtIndex:tappedIndexPath.row]]; 
      [self.taskArray removeObject:[self.taskArray objectAtIndex:tappedIndexPath.row]]; 
      newIndexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:1]; 
     } else { 

      NSUInteger newRowIndex = self.taskArray.count; 
      [self.taskArray addObject:[self.completedArray objectAtIndex:tappedIndexPath.row]]; 
      [self.completedArray removeObject:[self.completedArray objectAtIndex:tappedIndexPath.row]]; 
      newIndexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0]; 
     } 
     [self.tableView beginUpdates]; 
     [self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone]; 
     [self.tableView deleteRowsAtIndexPaths:@[tappedIndexPath] withRowAnimation:UITableViewRowAnimationNone]; 
     [self.tableView endUpdates]; 
} 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    NSInteger num = 0; 
    if (section == 0) { 
     num = self.taskArray.count; 
    } else { 
     num = self.completedArray.count; 
    } 
    return num; 
} 


-(void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{ 
    Tasks *taskToMove = [taskArray objectAtIndex:[sourceIndexPath row]]; 
    if (sourceIndexPath.row > destinationIndexPath.row) { 
     [taskArray insertObject:taskToMove atIndex:destinationIndexPath.row]; 
     [taskArray removeObjectAtIndex:(sourceIndexPath.row + 1)]; 
    } 
    else if (sourceIndexPath.row < destinationIndexPath.row) { 
     [taskArray insertObject:taskToMove atIndex:(destinationIndexPath.row + 1)]; 
     [taskArray removeObjectAtIndex:(sourceIndexPath.row)]; 
    } 
} 
-(IBAction)addCell:(id)sender{ 
    Properties2ViewController *pvc = [[Properties2ViewController alloc]init]; 
    [pvc setDelegate:self]; 
    [self presentViewController:pvc animated:YES completion:NULL]; 
    [pvc setModalTransitionStyle:UIModalTransitionStyleCrossDissolve]; 
} 
-(void)properties2ViewControllerDidEnterPropertiesSuccesfully:(Tasks *)t{ 
    if (![[t taskName] isEqual: @""]) { 
    [taskArray addObject:t]; 
    } 
    [self.tableView reloadData]; 
} 

Properties2ViewController.m

-(IBAction)dismiss:(id)sender{ 
    testTask = [[Tasks alloc]init]; 
    testTask.taskName = taskName.text; 
    testTask.timeInterval = datePicker.countDownDuration; 
    testTask.dateCreated = [NSDate date]; 
    if ([self.delegate respondsToSelector:@selector (properties2ViewControllerDidEnterPropertiesSuccesfully:)]){ 
     [self.delegate properties2ViewControllerDidEnterPropertiesSuccesfully:testTask]; 
    } 
    [self dismissViewControllerAnimated:YES completion:NULL]; 
} 

Свойства2viewcontroller - это модальный контроллер, который добавляет объект Task к taskArray.

+0

Попробуйте обновить весь вид таблицы, как вы измените более чем одну строку, вы перемещаете его из одной секции в другую. – Wain

+0

может предоставить экранные снимки для этого сценария. так что я могу помочь вам, как вы хотите - –

+0

Прежде всего используйте свойства для своих массивов (например, self.taskArray вместо taskArray). Таким образом, сеттеры и геттеры для ваших свойств будут вызываться автоматически, и вы можете избежать возможных ошибок памяти. Добавьте ленивый экземпляр для ваших массивов (например, - (NSMutableArray *) taskArray {if (! _taskArray) {_taskArray = [NSMutableArray array];} return _taskArray;}) и удалите его из viewDidLoad. Установите Исключительную точку останова, чтобы увидеть, в каком случае приложение приложения сработает. Способы отправки, когда вы добавляете данные ко всем пустым массивам. – Numeral

ответ

1

Вы пытаетесь перезагрузить строк, но то, что вы на самом деле хотите сделать, это удалить строку из раздела 0 и добавить его в раздел 1 или наоборот. Таким образом, в методе handlechecking вы должны написать что-то вроде этого:

-(void)handlechecking:(UITapGestureRecognizer *)t{ 

CGPoint tapLocation = [t locationInView:self.tableView]; 
NSIndexPath *tappedIndexPath = [self.tableView indexPathForRowAtPoint:tapLocation]; 
NSIndexPath *newIndexPath = nil; 

if (tappedIndexPath.section == 0) { 

    NSUInteger newRowIndex = self.sectionTwoArr.count; 
    [self.sectionTwoArr addObject:[self.sectionOneArr objectAtIndex:tappedIndexPath.row]]; 
    [self.sectionOneArr removeObject:[self.sectionOneArr objectAtIndex:tappedIndexPath.row]]; 
    newIndexPath = [NSIndexPath indexPathForRow:newRowindex inSection:1]; 
} else { 

    NSUInteger newRowIndex = self.sectionOneArr.count; 
    [self.sectionOneArr addObject:[self.sectionTwoArr objectAtIndex:tappedIndexPath.row]]; 
    [self.sectionTwoArr removeObject:[self.sectionTwoArr objectAtIndex:tappedIndexPath.row]]; 
    newIndexPath = [NSIndexPath indexPathForRow:newRowindex inSection:0]; 
} 
[self.tableView beginUpdates]; 
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationNone]; 
[self.tableView deleteRowsAtIndexPaths:@[tappedIndexPath] withRowAnimation:UITableViewRowAnimationNone]; 
[self.tableView endUpdates]; 
} 

Редактировать

Полная реализация других методов

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    self.sectionOneArr = [@[@"ololo", @"dsd", @"dsdfsf"] mutableCopy]; 
    self.sectionTwoArr = [@[@"ototo",@"dd", @"sdfsdfsd"] mutableCopy]; 
} 


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

    return 2; 
} 


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

    NSInteger num = 0; 
    if (section == 0) { 
     num = self.sectionOneArr.count; 
    } else { 
     num = self.sectionTwoArr.count; 
    } 
    return num; 
} 


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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"]; 
    if (!cell) 
     cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"UITableViewCell"]; 
    if([indexPath section] == 0){ 
     cell.textLabel.text = [[self.sectionOneArr objectAtIndex:[indexPath row]] uppercaseString]; 
     cell.imageView.image = [UIImage imageNamed:@"unchecked.jpeg"]; 
    } else if ([indexPath section] == 1) { 
     cell.textLabel.text = [[self.sectionTwoArr objectAtIndex:[indexPath row]] uppercaseString]; 
     cell.imageView.image = [UIImage imageNamed:@"checked.jpeg"]; 
    } 

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handlechecking:)]; 
    [cell.imageView addGestureRecognizer:tap]; 
    cell.imageView.userInteractionEnabled = YES; 

    return cell; 
} 


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 

    NSString * num = nil; 
    if (section == 0) { 
     num = @"One"; 
    } else { 
     num = @"Two"; 
    } 
    return num; 
} 
+0

, который не работает, к сожалению. У меня ошибка: я получаю сообщение об ошибке * Завершение приложения из-за неперехваченного исключения «NSRangeException», причина: '* - [__ NSArrayM objectAtIndex:]: индекс 0 за пределами для пустого массива' – EvilAegis

+0

user2533646, я отредактировал свой ответ и протестировал его на тестовом проекте. он должен работать – Numeral

+0

Хмм, он полуработал. иногда это сработало, но когда я нажал некоторые из строк, которые я получил: Завершение приложения из-за неотображенного исключения «NSInternalInconsistencyException», причина: «Неверное обновление: недопустимое количество строк в разделе 0. Количество строк, содержащихся в существующем разделе после update (0) должно быть равно количеству строк, содержащихся в этом разделе, перед обновлением (2) плюс или минус количество строк, вставленных или удаленных из этого раздела (вставлено 0, 1 удалено) и плюс или минус количество строки, перемещенные в или из этой секции (0 перемещено, 0 перемещено). ' – EvilAegis

0

Ваш код выглядит правильно, но я бы рискнул предположить, что проблема в вашем tableView: numberOfRowsInSection: method. Вы возвращаете правильное количество строк для каждого раздела? Должно выглядеть так:

if([indexPath section] == 0){ 
    return [taskArray count]; 
} else { 
    return [completeArray count]; 
} 
+0

Да, у меня действительно есть:/ – EvilAegis

Смежные вопросы