Apple has this to say:
Categories of the Root Class
A category can add methods to any class, including the root class. Methods added to NSObject become available to all classes that are linked to your code. Adding methods to the root class with a category can be useful at times, but it can also be quite dangerous. Although it may seem that the modifications the category makes are well understood and of limited impact, inheritance gives them a wide scope. You may be making unintended changes to unseen classes in your application; you may not know all the consequences of what you’re doing. Moreover, others working on your application, who are unaware of your changes, won’t understand what they’re doing.
My question is -- if I choose method names that are sufficiently weird that I am quite sure that no one else will use them (either at Apple or in my project), can I still get into trouble? Could there still be unexpected behavior? Performance implications?
If you're really quite certain that Apple would never add a method of that name, it's safe. If you want to enforce that certainty though, prefix the selector name. For example, Adium at one point added a -setObject:atIndex:
method to NSMutableArray
(yes, just a "cosmetic" wrapper over the existing API method -replaceObject:atIndex
. Very pointless)... it turned out to have the same name as an internal method, and veeeeery slightly different semantics. This caused crashes, but only on certain OSs. If it had been named something like -AISetObject:atIndex:
it would have been fine.
Performance implications for categories are minimal. I wouldn't worry about that aspect.
If your method names do not conflict with anything, and people who use them know what they do, you shouldn't run into any problems. Remember, a category adds extra methods, but not instance variables to a class. A subclass is more flexible, and is treated as an entire object, which responds to all superclass methods plus it's own. I would say make a subclass unless you can't or it's inconvenient to do so. Categories were made to be used, after all. I usually use categories when I have a framework and I need to add private methods to a publicly declared class.