I’m using tableView for displaying each tam tableView with different data.
when I coming back to the interface with all the tableView delegates i’m tantalizing the *list with a data (different arrays with fields) based on the the previous view
if(select = names )...
list = myData.Names;
if (select = workers)...
list = myData.Workers;
and so on…
and in the table delegates I use:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [list count];
}
But when I initializing the object for the table cells, How can I set exatcly the right object for the cell. now hard-coded I using:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
}
//HARD-CODED
names *s = [list objectAtIndex:indexPath.row];
cell.textLabel.text = names.firstName;
cell.detailTextLabel.text=s.lastName;
return cell;
}
When i setting the list to workers how can I know to cast every time to the right object? without writing millions of if?
for example if
if (select = workers)...
list = myData.Workers;
the [list count] will return the right number but i want to display data based on the list, how can i cast it so it automatically declare workers
workers *s = [list objectAtIndex:indexPath.row];
I think I understand your problem, so let me try to explain:
This can be easily solved using protocols and giving the cell configuring responsibility to the actual objects.
First, declare a protocol that your clases will conform to:
Now make some classes and make sure all of them conform to this protocol:
and:
etc…
In their implementation, each of them will handle the configuring of the cell differently:
and:
Remember the cell you receive is a custom cell that you created. For instance:
Now, in your delegate call:
And that’s it. No more if-else statements and no more casting.
Tip: Whenever you start seeing too many if-else statements in your class, dirtying up your code, start thinking about responsibilities. Should the object be in charge of figuring out how to configure the cell? Or could we delegate that task to another object?