Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString stringWithFormat return type, why is it "id"?

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.

like image 971
giampaolo Avatar asked Nov 07 '12 21:11

giampaolo


2 Answers

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.

like image 45
rooster117 Avatar answered Nov 15 '22 11:11

rooster117


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:@[]];
like image 68
WDUK Avatar answered Nov 15 '22 10:11

WDUK