自定义HeaderFooterView访问不良

时间:2017-07-08 21:04:23

标签: ios objective-c

在以下代码中,viewForHeaderInSection最后一行,我收到EXC_BAD ACCESS错误。

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    movies = [[NSArray alloc] initWithObjects:
           (NSArray*)[[Section alloc ] init:@"Z" movieNames:@[@"M", @"S"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"M" movieNames:@[@"Y", @"A"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"H" movieNames:@[@"M", @"F"] isExpanded:false], nil
           ];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ExpandableHeaderFoorterView* headerView = [[ExpandableHeaderFoorterView alloc] customInit:((Section*)movies[section]).genre withSection:section withDelegate:self];
    // BAD ACCESS
    return headerView;
}

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

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    cell.textLabel.text =  ((Section*)movies[indexPath.section]).movies[indexPath.row];
    return cell;
}

ExpandableHeaderFoorterView.m

- (id)customInit:(NSString*)title withSection: (NSInteger) section withDelegate :(id<ExpandableHeaderFooterViewDelegate>)delegate
{
    self.textLabel.text = title;
    self.headerSection = section;
    self.headerDelegate = delegate;
    return self;
}

1 个答案:

答案 0 :(得分:3)

您的自定义init方法的实现完全错误。那不是你在Objective-C中编写初始化器的方式。此外,由于它是初始化程序,因此名称应以init...开头。

由于您要扩展UITableViewHeaderFooterView,因此需要调用正确的超级初始化程序。

- (id)init:(NSString*)title withSection:(NSInteger)section withDelegate:(id<ExpandableHeaderFooterViewDelegate>)delegate {
    self = [super initWithReuseIdentifier:@"SomeUsefulIdentifier"];
    if (self) {
        self.textLabel.text = title;
        self.headerSection = section;
        self.headerDelegate = delegate;
    }

    return self;
}