The key to the problem you've run into rests on a subtle point about polymorphism in Objective-C. Because the language doesn't support method overloading, a method name is assumed to uniquely identify a method within a given class. There's an implicit (but important) assumption that an overridden method has the same semantics as the method it overrides.
In the case you've given, arguably the semantics of two methods are not the same; i.e., the first method returns a new string initialized with a 'stripped' version of the receiver's contents whereas the second method modifies the content of the receiver directly. Those two operations really aren't equivalent.
I think if you take a closer look at the way Apple names its APIs, especially in Foundation, it can really help shed light on some semantic nuances. For example, in NSString there are several methods for creating a new string containing a modified version of the receiver, such as
- (NSString *)stringByAppendingFormat:(NSString *)format ...;
Note that the name is a noun, where the first word describes the return value, and the rest of the name describes the argument. Now compare this to the corresponding method in NSMutableString for appending directly to the receiver:
- (void)appendFormat:(NSString *)format ...;
By contrast, this method is a verb because there's no return value to describe. So its clear from the method name alone that -appendFormat: acts upon the receiver, whereas -stringByAppendingFormat: does not, and instead returns a new string.
(By the way, there's already a method in NSString that does at least part of what you want: -stringByTrimmingCharactersInSet:
. You can pass whitespaceCharacterSet
as the argument to trim leading and trailing whitespace.)
So while it may seem annoying initially, I think you'll find it really worthwhile in the long run to try to emulate Apple's naming conventions. If nothing else it'll help make your code more self-documenting, especially for other Obj-C developers. But I think it'll also help clarify some semantic subtleties of Objective-C and Apple's frameworks.
Also, I agree that the internal details of class clusters can be disconcerting, especially since they're mostly opaque to us. However, the fact remains that NSString is a class cluster that uses NSCFString for both mutable and immutable instances. So when your second category adds another -strip
method, it replaces the -strip
method added by the first category. Changing the name of one or both methods will eliminate this problem.
And since a method already exists in NSString that provides the same functionality, arguably you could just add the mutable method. Ideally its name would correspond with the existing method, so it would be:
- (void)trimCharactersInSet:(NSCharacterSet *)set