从cellForRowAtIndexPath返回多个UITableViewCell子类?

fuz*_*oat 3 iphone cocoa-touch objective-c

我希望返回一些自定义的UITableViewCells,具体取决于我从savedGames存储在我的数组中返回的对象类型dataModel.我的问题是,我是以正确的方式来做这件事的吗?我之前没有这样做过,只是想确保我在正确的轨道上并没有遗漏一些明显的东西.

注意:新的单元格被分配并在其他地方初始化,这就是为什么它没有显示在下面的代码中.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger row = [indexPath row];
    SharedDataModel *dataModel = [SharedDataModel sharedInstance];
    id genericGameAtRow = [[dataModel savedGames] objectAtIndex:row];

    if([genericGameAtRow isMemberOfClass:[GameZoneOne class]]) {
        CellZoneOne *cell = [tableView dequeueReusableCellWithIdentifier:@"ZONEONE_ID"];
        return cell;
    }

    if([genericGameAtRow isMemberOfClass:[GameZoneTwo class]]) {
        CellZoneTwo *cell = [tableView dequeueReusableCellWithIdentifier:@"ZONETWO_ID"];
        return cell;
    }
    return nil;
}
Run Code Online (Sandbox Code Playgroud)

编辑:快速问题返回nil底部有用,我知道它避免了没有返回值的方法,但如果没有"if"s fire你将得到一个"必须返回一个单元格"错误.显然,覆盖所有可能的选项很重要,但最终返回不会更好地返回默认(vanilla)UITableViewCell吗?... 只是好奇.

Pey*_*loW 5

是的这是一个正确的解决方案.

我个人会远离-[id<NSObject> isKindOfClass:],因为它通常是一个糟糕的建筑的标志.相反,我会gameZonesavedGames数组中的所有可能类添加一个属性.并明确要求它的区域/类型.