objective c - Pros and cons of using "id" as the return type of a custom "init" method, instead of a pointer to that class? -


assume following objective-c class:

@interface appliance : nsobject {     nsstring *productname;     int voltage; } @end 

what pros , cons of implementing init method instead of b?

a) -(id)initwithname:(nsstring *)name; b) -(appliance *)initwithname:(nsstring *)name; 

i see both work in xcode, i.e. both result in valid appliance instance. "a" seems standard among books i've read , codebases i've looked at, , i'm wondering why is.

oh, reopen. :-)

indeed, did not ask difference id vs. instancetype. , -init… answer non-asked q easy: there no difference, because compiler converts id instancetype silently.

you asked id vs. customclass*. , different answer me: customclass* subclass had cast result of superclass' designated initializer. let's have example:

@interface baseclass : nsobject - (baseclass*)initwithwhatever; // typed class, designated initializer @end  @implementation baseclass - (baseclass*)initwithwhatever // typed class {   self = [super init]; // what's return type of -init (nsobject)?   … } @end  @interface subclass : baseclass // first problem: announce in interface, class overwrites // method of base class. doing have change return type. ugly. // if not redeclare -initwithwhatever inherited baseclass, still // having baseclass* return type. truth? really?  // however, not overwrite here, have new initializer. - (subclass*)initwithsomethingelse; @end  @implementation subclass - (subclass*)initwithsomethingelse {   // second problem:   // first, have execute superclass' designated initializer   self = [super initwithwhatever];   // wait minute!    // self reference subclass. return value of -initwithwhatever has type    // baseclass*. assign reference of base class reference of subclass:    // compiler error, false positive. code correct.   // have cast. ugly, ugly, ugly. @end … // third problem: subclass *object = [[subclass alloc] initwithwhatever]; // typing -initwithwhatever baseclass* lead compiler error here again.  // compiler error, false positive. code correct. 

to make long story short: without mass of castings impossible type initializers concrete class.


Comments