How Safe Are Objective-C Categories?

Objective-C categories are extremely useful, but there are some problems with this power. They are presented mainly in two forms, which I know of:

  • Two categories are trying to add the same convenience method. In this case, undefined is used. If you are careful not to add too many methods or to use especially common method names, the first problem will almost never be a problem.
  • New methods are added to the class by a writer who encounters a category. In this case, the category overrides the class method. Since the class cannot be under my control, I am more concerned about this problem.

Changes in the opposite direction should be safe enough, but the introduction of interfaces or the addition of convenient methods look more dangerous. I know that Cocoa seems to use it quite a lot for the convenience of methods, but again, the base class is under it. I think that maybe they just use categories to reduce dependencies, so the String class may have convenient methods for working in Cocoa, but if you are not using Cocoa, it does not retract.

So how safe are the categories / what guidelines exist to ensure their safety?

+4
source share
2 answers

Usually, when extending code that is not under your control (for example, Foundation), it is traditional to use a prefix or suffix for the method name to avoid such disagreements.

An example from Peter Hosey performs the main topic of the topic :

@interface NSObject (PRHPerformOnMainThread) - (id) performOnMainThread_PRH; @end 

This is not a great solution, but if you are worried about fragility, this is a good idea.

+6
source

I found the Google Objective-C Style Guide useful and includes an agreement to help avoid the clashes you mentioned.

+4
source

Source: https://habr.com/ru/post/1301886/


All Articles