I'm confused about the return type of factory methods in Objective-C.
This post: NSString stringWithFormat return type, why is it "id"? should resolved my confusion. But, the first line of the accepted answer does not make sense to me.
If I can't prevent subclassing (right?), and I can override class methods (ie. the factory methods), then don't I have to always return id
?
It's an API design decision. Subclassing cannot be prevented, but the API can be designed such as it is strongly discouraged. That's precisely the case of NSNumber
.
NSNumber
is a class cluster, meaning it is an abstract class with several private subclasses. Users of this class are normally not supposed to create their own subclasses, hence the design decision of returning NSNumber *
instead of id
.
Note that this cannot be done with other class clusters such as NSArray
or NSString
, since they have public subclasses.
id
is used for flexibility towards subclassing, so not using it is a way of discouraging the clients to subclass that class.
Incidentally, as I already mentioned here, as per today we have a better alternative to the id
return type, namely instancetype
. You can read more on the subject here.