Alex Rivera | Logout

Purpose of 'instancetype' keyword in 'objectWith' methods?

Asked 2013-04-23T06:29:48.773
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
Edit
Report

1 Answer

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.

answered 2013-04-23T06:50:04.467

Your Answer