Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C return types: "-(id) init" vs "-(ClassName *) init"

I was following this beginner tutorial http://www.raywenderlich.com/1797/ios-tutorial-how-to-create-a-simple-iphone-app-part-1, and I had a question regarding this class and its implementation here:

 RWTScaryBugData.h

 @interface RWTScaryBugData : NSObject

 @property (strong) NSString *title;
 @property (assign) float rating;

 - (id)initWithTitle:(NSString *)title rating:(float)rating;
 @end

RWTScaryBugData.m

@implementation RWTScaryBugData

@synthesize title = _title;
@synthesize rating = _rating;

- (id)initWithTitle:(NSString *)title rating:(float)rating {
    if ((self = [super init])) {
        self.title = title;
        self.rating = rating;
    }
    return self;
}

@end

I'm looking at this initializer:

 - (id)initWithTitle:(NSString *)title rating:(float)rating {
 }

Instead of writing it like that, I could also write it like this:

  - (RWTScaryBugData *)initWithTitle:(NSString *)title rating:(float)rating {
    }

Can anyone tell me the difference? Or, if it doesn't really matter?

like image 927
Heisenberg Avatar asked Aug 22 '14 20:08

Heisenberg


Video Answer


1 Answers

Returning id instead of the class was a convention in Objective-C used to allow subclasses to override that initializer and return their type. For example, for a long time the array class method on NSArray returned id so that NSMutableArray could override that method and return a mutable array, so both of these were possible:

NSArray *array = [NSArray array];
NSMutableArray *mutableArray = [NSMutableArray array]; // Wouldn't be possible if the method returned (NSArray *)

The problem with this was that you could also say:

NSString *string = [NSArray array]; // bad

and that would typecheck. Apple introduced instancetype as a new return type, which returns the class in which instancetype declaration is being used. Today, the array method returns instancetype so that the first 2 examples above typecheck, but the bad example won't typecheck.

More more details, see the NSHipster article on the subject.

like image 61
MaxGabriel Avatar answered Oct 21 '22 14:10

MaxGabriel