What are the advantages and disadvantages of using categories? Why and when do we need them?

What are the advantages and disadvantages of using categories? Why and when do we need them?

+4
source share
1 answer

Benefits:

  • You can extend any class, even those for which you have no source. Look, for example, at the UI extensions Apple added to the NSString class for rendering, getting metrics, etc.

  • Since you have access to all instance variables, categories provide you with a good way to structure your code through compilation units using logical grouping instead of using the โ€œeverything should be in one fiscal placeโ€ approach, such as Java.

Disadvantages:

  • You cannot safely override methods already defined by the class itself or another category.

AFAIK, languages โ€‹โ€‹do not give any guarantees as to which implementation will actually be called if you try something like:

 @interface Foo { } - (void) method; @end @interface Foo (MyCategory) - (void) method; @end 
+6
source

All Articles