dianovich
dianovich

Reputation: 2287

Subclassing a UIViewController implementing UITableView delegate and datasource: code reuse

I have some initialisation code in the viewDidLoad and viewWillAppear: methods that is used across a number of my UIViewController subclasses (which implement < UITableViewDataSource, UITableViewDelegate>):

-(void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
        style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tableView.frame = self.view.bounds
}

My thinking is to subclass UIViewController and include these methods in the subclass so as not to have to write this code in all my view controllers.

What are your thoughts on this? I'm wondering if this might give rise to issues retaining the tableView.

Cheers

Upvotes: 1

Views: 1665

Answers (1)

Di Wu
Di Wu

Reputation: 6448

Have you considered this structure:

UIViewController -> your_First_Level_Subclass_View_Controller -> your_Second_Level_Subclass_View_Controller

In the 1st level, you implement those reusable/tableView-related codes, but you don't actually use this 1st level controller. You then subclass this 1st level to create your 2nd level controllers, which are the ultimate controller that you are gonna use.

Upvotes: 2

Related Questions