The book I am reading says that after allocating an object I need to call the init function on the instance. However, I did not see any differences in the functionality of the class when I don’t call the init method. So what exactly is the init function doing ? Below is the interface for the simple class:
@interface Fraction: NSObject
{
int numerator;
int denominator;
}
-(void) print;
-(void) setNumerator: (int) num;
-(void) setDenominator:(int) den ;
@end
initis meant to initialize all necessary instance variables so that the object is in a defined state. Afteralloc, all ivars are set to0/nil/NULL, which might not be a permitted state for your object (for example,denominatorshould never be0).The
initmethod your class inherited fromNSObjectdoes nothing so if your class does not need to initialize any ivars you don’t have to implement your own. But it is good custom to always callinitright afteralloc, even if you know the method does nothing (who says this will remain true forever?).