2017-07-08 12 views
0

最後の行にviewForHeaderInSectionのコードがあります。EXC_BAD ACCESSエラーです。カスタムHeaderFooterView不正アクセス

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; 
} 

答えて

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; 
} 
+0

次の '@interface ExpandableHeaderFoorterView:UITableViewHeaderFooterView'を持つことで何が問題になりますか? – hotspring

+0

私は 'self = [super init]'を使うと知りました。カスタムinitメソッドは 'init'で始まります。したがって、メソッド名を 'customInit'から' initCustom'に変更し、 '@interface ExpandableHeaderFoorterView:UITableViewHeaderFooterView'をそのままにしておけば、あなたの解決策は正しいでしょう。答えを提供してくれてありがとう、ありがとう! – hotspring

+0

私はこのメソッドの名前でこの問題を見落としたとは思えません。はい、 'init ... 'で始めるべきです。また、あなたが 'UITableViewHeaderFooterView'を拡張していることを反映するために答えを更新しました。適切なスーパーイニシャライザを呼び出す必要があります。 – rmaddy

関連する問題