Voloda2 Voloda2 - 5 months ago 11
iOS Question

UITableView: I want to use an approach in which it is easy modify sections and rows (add, remove).

Our app has changed every month. It is very hard to modify sections and rows (add, remove). I need to scan every UITableViewDelegate's method and changed it. I'm using switch-case approach. I'm need more elegant approach.

I posted my code for two methods but in reality I have to modify 5 methods.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger rows;

switch (section)
{
case 0:
{
rows = 3;
break;
}
case 1:
{
rows = 4;
break;
}
case 2:
{
rows = 4;
break;
}
case 3:
{
rows = 4;
break;
}
case 4:
{
rows = 7;
break;
}

default:
rows = 1;
break;
}

return rows;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (indexPath.section)
{
case 0:
{
switch (indexPath.section)
{
case 0:
{
break;
}
case 1:
{
break;
}
case 2:
{
break;
}
default:
break;
}

break;
}
}
}

Answer

Create a class say TableManager

Pass your table view to this class and let this class provide the data for all your tableviews. Differentiate between the tableviews by settings tag values to them.

So now you will have control of all your tableviews in this one class.

Instead of the numbers in the switch case use enum. It will increase readability in your code.

Depending upon your actual requirement you can manipulate this class's behavior from a plist perhaps.

Let me provide some code:

Define an enumerator

typedef enum { FIRST_TABLE, SECOND_TABLE, THIRD_TABLE } TableViews;


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

[TableManager getNumberOfRowsForTableView:tableView];

}

In your TableManager

+ (NSInteger)getNumberOfRowsForTableView:(UITableView*)theTableView
{

if(theTableView.tag == FIRST_TABLE) //FIRST_TABLE is an enum
{
 //Your conditions goes here
 return 3;
}

}