Inherit from two classes

旧巷老猫 提交于 2019-12-12 05:48:47

问题


I am creating an universal iOS app, i.e. it will run on the iPhone and iPad. I now have a UIViewController that will be displayed on both, but differently. On the iPhone, it will contain a UITableView, on the iPad an AQGridView. The data will be the same. Both controllers will therefore share a lot of methods and instance variables.

Usually, I would create a UIViewController subclass with my methods and instance variables and then create two subclasses of this class where I put the stuff specific for the device.

The problem I'm facing now is that the iPhone version of my subclass should also inherit from an other class with some nice methods:

            UIViewController sublcass                   Some Other Class
                        |                                      |
            -------------------------------    -----------------
            |                             |    |
      iPad sublcass                 iPhone subclass

Adding the iPad version as a subclass of the iPhone sublcass is not possible as Some Other Class is designed to be used with a UITableView.

I'm pretty sure this is not possible in Objective-C but I wanted to ask before going ahead and creating a huge copy-&-paste mess. So: any suggestions on how to keep my code simple?


回答1:


Yes, multiple inheritance is not possible in Objective C. However with clean and logical design it is not necessary and could be replaced with protocols. However if it is not the case for you (however, I have some doubts about that) I suggest you to check the decorator design pattern.

Even if decorator pattern doesn't fit your needs I suggest you to use aggregation instead of inheritance (well, that is what decorator actually uses).



来源:https://stackoverflow.com/questions/6168728/inherit-from-two-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!