Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How safe are Objective-C categories?

Tags:

objective-c

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

  • Two categories attempting to add the same convenience method. In this case, it is undefined which one is used. If you are careful - not adding too many methods or using particularly common method names - the first problem should almost never be an issue.
  • New methods being added to a class by a writer that clash with a category. In this case the category overrides the class method. Since the class may not be under my control, I am more worried about this problem.

Backporting changes should be fairly safe, but implementing interfaces or adding convenience methods seem more dangerous. I know that Cocoa seems to use it for convenience methods quite a lot, but then again the base class is under there control. I think maybe they are just using the categories to reduce dependencies - so a String class can have convenience methods for working in Cocoa, but if you don't use Cocoa, it isn't pulled in.

So, how safe are categories/what guidelines are there for keeping them safe?

like image 914
Casebash Avatar asked Dec 30 '22 01:12

Casebash


1 Answers

Usually, when extending code not under your control (e.g. Foundation), it's traditional to use a prefix or suffix on the method name to avoid these sorts of collisions.

Example from Peter Hosey's perform on main thread category:

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

It's not the most beautiful solution, but if you're worried about fragility it's a good idea.

like image 188
Colin Barrett Avatar answered Jan 15 '23 05:01

Colin Barrett