From NSHipster, a great site that Objective-C developers should be reading:
instancetype, the compiler will correctly infer that the result of
+personWithName:is an instance of a
Perfect timing: I created a need for this a few days ago. As I was migrating The Magazine to Core Data, I built a simple convenience-utility superclass for my
Author classes to inherit that mimics my PHP model utilities:
@interface MAManagedObject : NSManagedObject + (MAManagedObject *)createWithID:(NSString *)idStr; + (MAManagedObject *)findByID:(NSString *)idStr; + (NSArray *)findAll; ... @interface Issue : MAManagedObject ...
That way, I could easily get instanaces like this:
Issue *issue = [Issue findByID:@"whatever"];
But that would throw a compiler warning:
issue expects an
Issue * but was being assigned, as far as it knew, a
MAManagedObject *. So instead, I had to inelegantly cast the result of each call:
Issue *issue = (Issue *)[Issue findByID:self.issueID];
I just changed the method declarations in
MAManagedObject to return
@interface MAManagedObject : NSManagedObject + (instancetype)findByID:(NSString *)idStr; ...
And now the compiler is satisfied when assigning subclass calls without the casts.