Sunday, April 3, 2016

Objective C Subclass vs Category

We all know what are sub classes. Whenever we take a ViewController or a control like Button or TextField, we see they are inherited from the respective parent classes as shown below.



  @interface MyViewController : UIViewController
  @interface MyButton : UIButton

  @interface MyTextField : UITextField


Then, What are categories?

If I want to add my own functionality, I mean some new methods which are not available in the parent class, I can write categories as shown below.



  
UIImage+ ImageAdditions.h
  @interface UIImage (ImageAdditions)


Have a look at my Objective-C Categories post to get clear idea on Categories.

Now, we know what are Subclasses and what are Categories.

Both are there to add some customized functionality. Then what is the difference between those two and where they fit exactly, I mean what is the scope of those.

When to Subclass:


When we need to override any existing functionality of a parent class, we need to go for Subclasses. For example, I want to override the 'didSelectRowAtIndexPath' method of UITableView, Whenever I use this sub class in my application, on selecting a row, I want to execute my custom functionality. In this case it is better to go for the Subclassing. Because you are just customizing the existing functionality, not writing any thing new here.



                         



When to Categorize:

When we need to add some new functionality to the existing class, we need to go for categories. For example, I want to add a method in UIImage class, Where calling it gives me a circular image. In this case, you don't have any thing for this in UIImage class, You are writing a new functionality to the UIImage class. So, here is the correct choice is Categories.


Hope this post is useful. Feel free to comment in case of any queries.