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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With