iOS Dev Nugget 60 Use instancetype


Need to run a code review on your codebase? Hire me

instancetype is an Objective C keyword that is meant to be used as a method return type representing the type of the current (sub)class. Generally, you'd want to use it in constructor-type methods. It's preferable to returning id or the specific class so that it works nicely without requiring casting or giving up type-checking. E.g.

@interface MyClass : NSObject
+ (MyClass)myClassWithValue1:(NSString*)aString;
+ (id)myClassWithValue2:(NSString*)aString;
+ (instancetype)myClassWithValue3:(NSString*)aString;

@interface MySubClass : MyClass

If you call +myClassWithValue1: when working with MySubClass, you'd need to cast it back to MySubClass. If you use myClassWithValue2:, you loose type checking. If you use myClassWithValue3, you get the best of both worlds.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues