Inherit from two classes
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 w开发者_如何学运维ill 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?
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).
精彩评论