0

When writing a NSString category/extension, does it matter if i use

return [self stringWithFormat:units[i], value/10.0];

or

return [NSString stringWithFormat:units[i], value/10.0];

is there an advantage to using self or is this one of those user preferences things

highboi
  • 673
  • 7
  • 28
  • `self` indicates instance methods (at least for me), but stringWithFormat is a static method, therefore use `[NSString ...]`. – luk2302 Nov 28 '16 at 16:59
  • 1
    @luk2302 `self` refers to the current class in a class method. – Rob Napier Nov 28 '16 at 17:00
  • @RobNapier therefore I wrote "indicates", I added a clarification – luk2302 Nov 28 '16 at 17:02
  • @luk2302 so if im understanding correctly, use self for (-) methods and NSString for (+) methods? – highboi Nov 28 '16 at 17:06
  • You should probably do whatever Rob advices since I do not have as much experience as he does and have not encountered and situations where `self` was a bad choice. – luk2302 Nov 28 '16 at 17:08

1 Answers1

3

(I assume that the extension method in question is a class method. There seems to be some confusion that's leading to down votes; this is a very good question.)

As a general rule, you should use self here. That way if a subclass has overridden the method, you will use the subclass's version of that method. Subclasses can override class methods just like they can override instance methods.

That said, NSString is a kind of funny case because it's a class cluster, and so it would be very surprising for any of its hidden subclasses to override this class method (and subclassing it yourself is tricky at best). So in practice, for NSString, it almost certainly doesn't matter. But as a rule, you have the right intuition: use self unless you explicitly don't want to use the subclass's implementation.

There is one big exception to this: +initialize. You need to be very thoughtful about what class you're in, because this may be called multiple times. If you're overriding +initialize, see its documentation about how to implement it properly.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • for the most part, im just writing extensions to take a string and parse it to a specific format, for example a currencyWithChange, numberWithoutDecimal, etc... `use self unless you explicitly don't want to use the subclass's implementation.` was what i needed to hear, thanks – highboi Nov 28 '16 at 17:15