iOS – Usage of Category

Category

What is Category and why do we need this in iOS Development?

First thing you need to know, Category is not a subclassing (Inheritance). Category is simply a concept of adding methods to your existing class. No need to create the instance of your category class as it will be called from your Main class instance.

Not Getting? Lets take an example….

We have class Car, inside it have methods getCarSpeed, getCarColor.

We have created a Category of Car Class.

Now let us call it from UIViewController.

If you notice here we have created the instance of the Car but we are calling the method of Car+Modified.

Try it with your self for better understanding.

Adding methods in existing Class NSString

Here we have added the ‘reverseString’ method to existing NSStirng Class. Now this method is available for use along with other methods of the NSSting.

Scenarios / Situations were we use Category

– Split the code according to the module (For each module go for different category)
– Add methods to iOS SDK classes Like NSString, UIColor, UIFont (Frequently used)

Leave a Reply