How to develop a common subclass for UIViewController, UITableViewController, and UICollectionView controller?

This task is seemingly impossible. You’d like to have some common methods to use for all three controllers. Because of the apparent lack of the ability to “interject” a UIViewController subclass into a UITableViewController, I just never used it. When UICollectionViewController came out, though, I was determined to find a way to do this.

At first I tried using a UIViewController – .m and .h – with macros, but I never got it to work properly. Finally, I created two files, ¬†BaseClass.h and BaseClass.m. In the former, I just declared the methods themselves along with any public properties. Then in the implementation file, I coded the methods. Note there is no “@interface…” or “@implementation”.

Finally, I created three subclasses, STViewController, STTableViewController, and STCollectionViewController, and between the interface declaration and “@end”, included the base class file. Voila – works like a champ.

What’s even more amazing is that Xcode’s editor works just find with these naked methods when editing BaseClass.m – it parses them and highlights errors just as it would for a normal class!

Advertisements

2 thoughts on “How to develop a common subclass for UIViewController, UITableViewController, and UICollectionView controller?

    • Blog posts like this prompt thinking. I am using this technique in an app now with great success, after having to essentially support 3 base classes that I had to keep synchronized by hand. Not one is making you use it. As people say, YMMV.

      Its interesting that this same sort of topic has come up in Swift. People are asking for “mixed ins” (something like that), where you define a protocol, but get to actually include a method in the protocol that all adopters inherit. That of course would provide the same outcome as my technique here.

      Unfortunately this technique is not portable to Swift, so once again I will need to create 3 subclasses and keep them in synch manually (or keep the subclasses in Objective-C, and further subclasses in Swift).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s