When to use Categories Objective-C?

Apollo picture Apollo · Apr 15, 2014 · Viewed 16.6k times · Source

If I have a method to attach an animation to an UI Element, instead of copy/pasting the code for this method into many viewcontrollers, can I just create one class to hold the method and then import it?

I assume it doesn't make sense to use a category in this instance because I need this method in multiple viewcontrollers, and a category is an extension of a single viewcontroller.

Answer

Wain picture Wain · Apr 15, 2014

A category is an extension of a class, not of a specific instance of a class. And, any modification that a category makes to a class is available to all subclasses (as with other methods on classes in OOP).

So, if you add a category on NSObject, basically all classes in your entire app have access to the methods in that category - hence you need to be very careful what methods you add there.

Whether you add a category or a helper class is personal preference in a lot of cases, both will work.