【发布时间】:2013-05-17 20:36:19
【问题描述】:
长篇大论:
我的一位同事向我寻求帮助。我是一名 C# 开发人员,他是一名 iOS 开发人员,阅读彼此的代码有时会给我们一些很好的见解。
他正在编写一些函数,该函数需要返回一个基本类型为UITableViewCell 的对象,并以整数作为输入。实际返回类型是UITableViewCell 的子类。他问我是否知道比这样简单的开关更好的解决方案:
- (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];
//Do PersonInfoCell specific stuff with cell
return cell;
break;
}
case 1: {
NSString *CellIdentifier = @"photoCell";
PhotoCell *cell = (PhotoCell *)[self makeCell:CellIdentifier];
//Do PhotoCell specific stuff with cell
return cell;
break;
}
default:
return nil; //Don't care about this atm. Not the problem.
break;
}
}
- (id *)makeCell:(NSString *)cellIdentifier
{
id cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[PhotoCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; // <---- how does this method know it is a PhotoCell I want?
//PhotoCell???
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
【问题讨论】:
标签: c# objective-c uitableview generics