Reputation: 18774
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
Upvotes: 1
Views: 271
Reputation: 28103
allocating an object I need to call the init function on the instance
can be treated as
allocating an object I should call the init function on the instance
Init is generally used to initialize instance variables within the class.
In the init method of the NSObject class, no initialization takes place, it simply returns self .
Upvotes: 1
Reputation: 135588
init
is meant to initialize all necessary instance variables so that the object is in a defined state. After alloc
, all ivars are set to 0
/nil
/NULL
, which might not be a permitted state for your object (for example, denominator
should never be 0
).
The init
method your class inherited from NSObject
does 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 call init
right after alloc
, even if you know the method does nothing (who says this will remain true forever?).
Upvotes: 1