views:

328

answers:

2

Hi. Does anyone know a simple way to manage several tableViews in one viewController? Here is how I've been doing it so far:

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
if(tableView == self.tableView1) 
return 1;
else if(tableView == self.tableView2) 
return 2;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if(tableView == self.tableView1) 
return @"bla";
else if(tableView == self.tableView2) 
return @"blabla";
}

-(NSString *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView == self.tableView1) 
...
else if(tableView == self.tableView2) 
...
}

I find it really annoying that I have to use an if/else statement for EVERY SINGLE delegate method. Plus, it is really hard to read when there are many tableViews. Besides, I have the same problem with NSURLConnection, etc... As soon as I have several objects that respond to the same delegate protocol, things get messy.

What is the best way to make things simpler? Thanks

A: 

You could use selectors and some kind of identifier for the table views (the UIView tag, for example). Something like this:

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  return [self performSelector:NSSelectorFromString([NSString stringWithFormat:@"tableView%d:titleForHeaderInSection:", tableView.tag])];
}

Of course you will need to have one method for each of your table views. Suppose your two tables have a the tags 100 and 101, you will have then tableView100:titleForHeaderInSection and tableView101:titleForHeaderInSection.

Marco Mustapic
That is quite convenient! Thanks.
Supernico
+2  A: 

One method which I have often used is to actually have the delegates and data source for the two UITableViews be different objects. This way, your view controller doesn't have to switch back and forth, and your code is overall cleaner and simpler.

chpwn
That makes sense. I'll do that next time I have to handle several delegating objects. Thanks.
Supernico