Search code examples
iosobjective-ciphoneuitableviewios7

Bad Access error on long tap on section of UItableview


Here is my code.Which I use to display content on the section of table and reload on section click

    -(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    NSArray *arr=[[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
    CustomCell *cellHeader=[arr objectAtIndex:0];
   UIButton *button = [[UIButton alloc] initWithFrame: CGRectMake(0.0, 0.0, 320.0, 80.0)];
    button.alpha = 0.7;
    button.tag=section;
    /* Prepare target-action */
    [button addTarget: self action: @selector(handleTap:) forControlEvents: UIControlEventTouchUpInside];
    [cellHeader.contentView addSubview: button];
    objISLMenu= [self.dataArray objectAtIndex:section];
    NSString *titleStr= objISLMenu.displayName;
    cellHeader.titleLabel.text=titleStr;
    if(section ==selectedSection){
        //bg as red
        [cellHeader.contentView setBackgroundColor:[UIColor redColor]];
        //text as white
        [cellHeader.titleLabel setTextColor:[UIColor greenColor]];
    }
    else{
        //bg as white
        [cellHeader.contentView setBackgroundColor:[UIColor redColor]];
        //text as white
        [cellHeader.titleLabel setTextColor:[UIColor greenColor]];
    }
    return cellHeader.contentView;
    }

-(void)handleTap:(UIButton*)sender
{
NSLog(@"%ld",(long)sender.tag);
if(selectedSection==sender.tag){
    //clicked is same as expanded
    selectedSection=-1;
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationNone];
}
else{
    NSLog(@"%ld",(long)sender.tag);
    long removesectionid=selectedSection;
    selectedSection=sender.tag;
    [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationNone];
    if(removesectionid!=-1){
        [self.tableview reloadSections:[NSIndexSet indexSetWithIndex:removesectionid]  withRowAnimation:UITableViewRowAnimationNone];
    }
    if([tableview numberOfRowsInSection:sender.tag] ==0 )
    {
         [self updateViewControllerWithIndex:sender.tag];
    }
}

}

I am using this code to show data on section reload section data on button click.Long press on section gives me a bad access error.


Solution

  • Instead of adding subview on content view add on view