Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use Categories Objective-C?

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.

like image 520
Apollo Avatar asked Apr 15 '14 13:04

Apollo


1 Answers

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.

like image 90
Wain Avatar answered Oct 05 '22 23:10

Wain