Multinerd Multinerd - 4 days ago 7
iOS Question

When writing a category, should i use self or the category name

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

Answer

(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.

Comments