【发布时间】:2014-12-24 02:27:33
【问题描述】:
我有一个genericTableViewController - GTBVC - 类,它被当前另外两个视图控制器所占用,每个视图控制器都有自己的数据数组,这些数据数组被传递到这个GTBVC。
目前我的代码如下所示:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id object = [self.genericArray objectAtIndex:indexPath.row];
NSString *textNameOfObject = [[self.genericArray objectAtIndex:indexPath.row] performSelector:@selector(name)];
#warning - todo: Create a polymorphistic method for each uitableviewcells.
if([object isMemberOfClass:[OXPersonModel class]]){
OXFriendTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellFriendIdentifier forIndexPath:indexPath];
cell.friendNameLabel.text = textNameOfObject;
[PKQuickMethods setCornerRadiusForView:cell.friendImageView withCornerRadius:CGRectGetWidth(cell.friendImageView.frame)/2];
cell.friendImageView.image = [UIImage imageNamed:@"image"];
[cell.friendImageView setContentMode:UIViewContentModeScaleToFill];
return cell;
}
else if([object isMemberOfClass:[OXTagPlaceCountModel class]]){
OXTagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTableViewCellTagIdentifier forIndexPath:indexPath];
cell.tagNameLabel.text = textNameOfObject;
cell.tagPlacesCountLabel.text = [[self.genericArray objectAtIndex:indexPath.row] performSelector:@selector(totalPlacesCountString)];
return cell;
}
return nil;
}
到目前为止,这种方法还不错。然而,因为我希望让我的代码在未来具有可扩展性——当我扩展程序以适应其他单元和产品类型时——我需要确保它易于实现。
想到了多态性。我在想每个 UITableView 子类都需要实现一个通用方法名称,例如-[cell updateForModelObject:],这样最终cellForRowAtIndexPath 将只有几行代码。
但我发现自己想象我仍然需要根据它们的标识符找出哪些单元格要出列。要出列的单元格取决于 self.genericArray 中的对象类型。
如何在不使用任何 if 语句的情况下使 cellForRowAtIndexPath 多态中的当前代码?
【问题讨论】:
标签: ios objective-c uitableview ios7 polymorphism