将新部分插入UITableView导致崩溃

时间:2013-07-23 08:19:03

标签: ios uitableview

我正在努力在UITableView中插入新的部分。基本上我想要实现的是: - 我正在尝试创建日历,其中每个SECTION对应于每年。每个部分有30个细胞。

第一部分加载得很好但是当我去第一部分的第8个单元格然后我尝试插入新部分

sectionNo =1; //in viewDidLoad method 

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *) cell              forRowAtIndexPath:(NSIndexPath *)indexPath
{
if(indexPath.row == 10 && indexPath.section == sectionNo-1)
{
    sectionNo = sectionNo+1;
    [mainTable insertSections:[NSIndexSet indexSetWithIndex:sectionNo-1] withRowAnimation:UITableViewRowAnimationNone]; //APPLICATION CRASHES HERE  ERROR IS "Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
"
}
   }

//部分数量为

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return sectionNo;    //count of section
}

//每个部分的行数

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 12; 
}

//行方法的CEll读为

- (UITableViewCell *)tableView:(UITableView *)tableView
     cellForRowAtIndexPath:(NSIndexPath *)indexPath
 {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:MyIdentifier] autorelease];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
  cell.textLabel.text = @"Hello";
return cell;
}

有趣的是,当我不快速滚动它然后它不会崩溃。但如果我从第10行缓慢滚动到11,那么有时它不会崩溃 我在这里做错了什么

2 个答案:

答案 0 :(得分:1)

编辑:我们解决了这个问题:

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{ 
  if(indexPath.row == 10 && indexPath.section == _sectionNo-1) 
  { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     [self addSectionToTableView]; 
    }); 
  } 
} 

- (void)addSectionToTableView{ 
_sectionNo++; 
 [_mainTable insertSections:[NSIndexSet indexSetWithIndex:_sectionNo-1] withRowAnimation:UITableViewRowAnimationNone]; 
}

答案 1 :(得分:0)

这个代码可能导致问题:

if(indexPath.row == 10 && indexPath.section == sectionNo-1)
{
    sectionNo = sectionNo+1;
    [mainTable insertSections:[NSIndexSet indexSetWithIndex:sectionNo-1] withRowAnimation:UITableViewRowAnimationNone];
}

将其更改为:

if(indexPath.row == 10 && indexPath.section == sectionNo-1)
{

    [mainTable insertSections:[NSIndexSet indexSetWithIndex:sectionNo-1] withRowAnimation:UITableViewRowAnimationNone];
    sectionNo = sectionNo+1;
}
相关问题