Joris Kluivers

I like to build software.

Instancetype

The always informational NSHipster points out a new addition to Objective-C in LLVM: instancetype.

Use this type as the return type of a method and the compiler knows the returned object will be similar in type to the class defining the method. This is also know as a related result type.

In Objective-C naming conventions play a significant role. Most importantly they are used to determine object ownership by taking into account the name of the returning method. ARC works because it knows what to do by looking at the method name.

The same naming conventions also hint the compiler about the returned object type. alloc/init methods are assumed to return an instance of the receiving class type.

1
2
// no need to cast from id to NSArray* here
NSArray *someArray = [[NSArray alloc] init];

From the LLVM documentation the related result type is assumed if:

  • the first word is alloc or new, and the method is a class method, or
  • the first word is autorelease, init, retain, or self, and the method is an instance method.

Using instancetype a related result type can be declared for any method.

1
2
3
@interface MyObject
+ (instancetype) convenienceMyObject;
@end

This is especially useful for convenience constructors.

Current API uses

A search reveals instancetype is already being used in several API’s and sample code:

  • [UINavigationController initWithNavigationBarClass:toolbarClass:]
  • Convenience constructors of UICollectionViewLayoutAttributes
  • initWithStyle: in iAdSuite sample code

Note that while the return type is already implied by its name, the initWithNavigationBarClass... is still using instancetype as its result type.