ios - Objective-C 继承重复代码问题

标签 ios objective-c

我有 FilesViewController , ShareViewControllerUICusomtTableViewCell包含 UICollectionView 的对象及其委托(delegate)方法:

- numberOfSectionsInCollectionView

- numberOfItemsInSection

- cellForItemAtIndexPath

所以最后一个方法看起来像这样:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SNFileCollectionViewCell *cell = (SNFileCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"FileCollectionViewCell" forIndexPath:indexPath];

    SNTestFile *file = [self.files objectAtIndex:indexPath.item];

    [cell setText:file.name];
    [cell setImage:file.image];

    return cell;
}

对于我在上面列出的所有这些对象,cellForItemAtIndexPath 方法做同样的事情 - 它创建单元格,因此为了优化我创建的代码 BaseViewController : UIViewController并立即将这个方法放在那里FilesViewControllerShareViewController继承自 BaseViewController并且对创建单元具有相同的功能,并且我不需要重复的代码。

但是作为 UICusomtTableViewCell这是另一个 UIViewController子类,我不能从 BaseViewController 继承,因为这是另一回事。

所以这意味着我不能继承我需要的部分功能,这意味着我需要复制代码,这不是一个好习惯,因为如果项目中的某些事情做同样的事情,好的程序员永远不会复制它。

你能提出什么建议?

所以这个想法只是将相同代码的一部分放在一个地方,然后我可以只修改一个点而不是很多点。你知道我的意思。

最佳答案

作为一个变体,您可以创建单独的类,我们将其命名为 blablablaHelper,它只有静态方法。添加方法 + (Cell *) createBlablabla:()...并在所有 3 个类中使用它,而不是做基类。

关于ios - Objective-C 继承重复代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166428/

相关文章:

ios - UITableView 捕捉到单元格

ios - 仅在 UITableView 中循环遍历 textFields

ios - Google API Bug - 归因不一致

ios - Firebase Auth iOS 用户匿名创建但不在控制台中显示

ios - 在动态 (Cocoa Touch) 框架内链接静态库

iphone - 在 iOS 中使用 Google Plus 分享图片

objective-c - 在运行时发现类的哪些实例变量被声明为 __weak

ios - Images.xcassets 中的 LaunchImage 与 Launchscreen.xib

ios - CGRectContainsPoint 不返回 YES 但在模拟器上该点在图像中

ios - FBSDKLikeControl 与 iOS10 不工作