我有 FilesViewController
, ShareViewController
和 UICusomtTableViewCell
包含 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
并立即将这个方法放在那里FilesViewController
和 ShareViewController
继承自 BaseViewController
并且对创建单元具有相同的功能,并且我不需要重复的代码。但是作为
UICusomtTableViewCell
这是另一个 UIViewController
子类,我不能从 BaseViewController 继承,因为这是另一回事。所以这意味着我不能继承我需要的部分功能,这意味着我需要复制代码,这不是一个好习惯,因为如果项目中的某些事情做同样的事情,好的程序员永远不会复制它。
你能提出什么建议?
所以这个想法只是将相同代码的一部分放在一个地方,然后我可以只修改一个点而不是很多点。你知道我的意思。
最佳答案
作为一个变体,您可以创建单独的类,我们将其命名为 blablablaHelper,它只有静态方法。添加方法 + (Cell *) createBlablabla:()...并在所有 3 个类中使用它,而不是做基类。
关于ios - Objective-C 继承重复代码问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26166428/