Both work, but which one would you use and why?
@implementation NSString (Extender)
-(NSString *) stringByTrimmingPrefix:(NSString *)strPrefix
{
while ([self hasPrefix:strPrefix])
{
self = [self substringFromIndex:strPrefix.length];
}
return self;
}
@end
or
@implementation NSString (Extender)
-(NSString *) stringByTrimmingPrefix:(NSString *)strPrefix
{
NSString *returnValue = [NSString stringWithString:self];
while ([returnValue hasPrefix:strPrefix])
{
returnValue = [returnValue substringFromIndex:strPrefix.length];
}
return returnValue;
}
@end
Option #2.
NSString is intended to be an immutable object. All of the standard “stringBy” methods on NSString return new autoreleased NSStrings.
While #1 also ends up returning a new NSString, it is at best semantically incorrect and at worst altering the referenced object of what was supposed to be an immutable object.