Objective-C categories are extremely useful, but there are some problems with this power. These come in basically two forms which I know of:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With