长话短说:
我的同事向我求助。我是一名C#开发人员,他是一名iOS开发人员,互相阅读代码有时可以获得一些有益的见解。
他正在编写一些函数,需要返回一个基础类型为UITableViewCell
的对象,并将整数作为输入。实际返回类型是UITableViewCell
的子类。他问我是否知道比简单的switch语句更好的解决方案:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (row) {
case 0: {
NSString *CellIdentifier = @"personCell";
PersonInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PersonInfoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
break;
}
case 1: {
NSString *CellIdentifier = @"photoCell";
PhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[PhotoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
break;
}
default:
return nil; //Don't care about this atm. Not the problem.
break;
}
}
我对C#的实现会是以下这样:
public UITableViewCell TableViewCellForRowAtIndexPath(UITableView tableView, NSIndexPath indexPath)
{
switch(indexPath.row)
{
case 0:
return MakeCell<PersonInfoCell>();
case 1:
return MakeCell<PhotoCell>();
default:
return null; //Still doesn't matter
}
}
public TCell MakeCell<TCell>() where TCell : UITableViewCell, new()
{
TCell cell = new TCell();
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
public class PersonInfoCell : UITableViewCell
{
//Dont care about implementation yet....
//TL;DR
}
public class PhotoCell : UITableViewCell
{
//Dont care about implementation yet....
//TL;DR
}
简短故事:
有人知道如何将我的C#通用代码转换为Objective-C等效代码吗?
更新1
我们基于Nicholas Carey的想法实现有误。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
switch (row) {
case 0: {
NSString *CellIdentifier = @"personCell";
PersonInfoCell *cell = (PersonInfoCell *)[self makeCell:CellIdentifier];
//使用 cell 执行 PersonInfoCell 相关操作
return cell;
break;
}
case 1: {
NSString *CellIdentifier = @"photoCell";
PhotoCell *cell = (PhotoCell *)[self makeCell:CellIdentifier];
//使用 cell 执行 PhotoCell 相关操作
return cell;
break;
}
default:
return nil; //暂时不关心此处,不是问题。
break;
}
}
- (id *)makeCell:(NSString *)cellIdentifier
{
id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[PhotoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; // <---- 这个方法如何知道我想要一个 PhotoCell?
//PhotoCell???
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}