Question

Why does the method [NSString stringWithFormat] return an id type? From the name I'm expecting it returns a NSString, not a generic pointer. Other classes follow this "rule". For example [NSNumber numberWithInt] returns a NSNumber, not an id.

I think it's not even justified from the fact that is something like a factory method.

Was it helpful?

Solution

You mention NSNumber, this doesn't have any direct subclasses, so it's safe for numberWithInt: to return a NSNumber*

NSString* (and other classes such as NSSet) return type id because they can have subclasses (NSMutableString and NSMutableSet respectively), which will inherit this method. As such, these inherited calls need to return an instance of the subclass's type, and due to the rules of method naming, you can't overload based on return type alone. As such, they need a common type between them all, which is id.

Update: Recent developments mean the keyword instancetype is now available. You may have noticed a lot of references to id are now replaced with instancetype. This keyword provides a hint to the compiler that the return type of the method is the same class of the receiver of the method.

For example (and I stress an example, this may not be the case in the actual framework):

NSArray:
- (instancetype)initWithArray:(NSArray*)array;

NSMutableArray:
// Inherits from NSArray

----

// Receiver is NSArray, method belongs in NSArray, returns an NSArray
[[NSArray alloc] initWithArray:@[]];

// Receiver is NSMutableArray, method belongs in NSArray, returns an NSMutableArray
[[NSMutableArray alloc] initWithArray:@[]];

OTHER TIPS

Because it is a static method on the class NSString and it is assumed to be returning the type of the object being called on. This is also dependent on the type since this can come from an NSMutableString.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top