11

Recent Objective-C compilers introduce the 'instancetype' keyword, which among other things can be used to provide typed collections. . .

I saw another purpose of instancetype, which was using it in 'objectWith' type methods on classes. For example:

@interface Car

    +(instancetype)carWithWheels:(NSArray*)wheels;

@end

The justification was that the compiler will do type checking for initWith methods, but not for 'objectWith' methods.

Besides being potentially easier to type, what is the benefit of using 'instancetype' in place of the actual class-name? Eg:

@interface Car

    +(Car*)carWithWheels:(NSArray*)wheels;

@end
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185

2 Answers2

35

By using instancetype, you're saying that subclasses will return an object of the subclass.

If we have

@interface Car

    +(instancetype)carWithWheels1:(NSArray *)wheels;
    +(Car *)carWithWheels2:(NSArray *)wheels;

@end

and

@interface VolkswagenBeetle : Car

@end

then +[VolkswagenBeetle carWithWheels1:] is guaranteed to return an instance of VolkswagenBeetle; but +[VolkswagenBeetle carWithWheels2:] might return a Buick, a Caddilac, or a ChittyChittyBangBang.

Simon
  • 25,468
  • 44
  • 152
  • 266
  • thanks. . . If I'm using a method on the base-class, I generally expect to be dealing at that level of abstraction. . Nonetheless, I can see now how this might be useful. – Jasper Blues Apr 23 '13 at 07:19
2

You can subclass Car and still benefit from instancetype. Of course you could achieve this using id, but you'd loose type checking which you gain from instancetype. I simply use it everywhere it's supposed to return object of current class (subclasses return object of that subclass), specifically in convenience methods and stuff.

There is a great answer which could help.

Community
  • 1
  • 1
MANIAK_dobrii
  • 6,014
  • 3
  • 28
  • 55