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