14 Aug 2011, 21:34
Generic-user-small

Don Ky (5 posts)

Hi guys, there is something I am still confused about after going through the objective-c screen casts:

`
-(id)initWithTitle:(NSString *)newTitle andRating:(int)newRating
{
    /*
    self = [super init]; //why? 
    if (nil != self) {
        self.title = newTitle;
        self.rating = newRating;
    }
        
    return self;
     */
    title = newTitle;
    rating = newRating;
    return self;
}
`

Why is the following piece of code necessary:

`
 self = [super init]; //why? 
    if (nil != self) {
        self.title = newTitle;
        self.rating = newRating;
    }
`

vs just typing:

`
    title = newTitle;
    rating = newRating;
    return self; 
`

Under the custom init method?

Thanks
23 Aug 2011, 01:47
Biopic_100x100_pragsmall

Bill Dudney (917 posts)

Hi Don,

Sorry to be so late getting back to you.

The call to super is not technically absolutely necessary today. But… you should always call your super classes designated initializer. For this object’s super class (NSObject) the init does not much more than setting the class, but for more involved objects it would be very bad to skip the super classes implementation.

For example if you were to override initWithFrame: on a UIView and not call super, very bad things would happen (not death or anything, but your view would be hosed).

Hope this helps!

  You must be logged in to comment