To complete the object, these step are required.
1)
Class *myClass = [Class alloc];
// This will allocate the memory required by every variable and the class
// and also return the class instance. The documentation says memory for
// all instance variable is set to 0.
2)
myClass = [myClass init];
// complete initialization
// From the documentation, the init method defined in the NSObject class
// does no initialization, it simply returns self.
The question:
I write a class
@interface Fraction : NSObject
- (void)print;
- (void)setNumerator:(int)n;
- (void)setDenominator:(int)d;
@end
@implementation Fraction
{
int numerator;
int denominator;
}
- (void)setNumerator:(int)n {
numerator = n;
}
- (void)setDenominator:(int)d {
denominator = d;
}
- (void)print {
NSLog(@"%i/%i", numerator, denominator);
}
And in the main.m
Fraction *fraction = [Fraction alloc]; // without the initialization
fraction.denominator = 3;
[fraction print];
This is what I get on the console
0/3
1) The value of numerator is 0. I didn't set the numerator and it print 0. This is strange, because integer default value should be undefined. How can this happen?
2) With alloc, the memory for all instance variable is set to 0. But, how can I set denominator to 3 and it still works. To store value to the denominator (int) variable we need 4 bytes memory allocated.
3) The last question, when I do
- (id)init {
self = [super init];
if (self) {
// Initialize self.
}
return self;
}
The init method was inherited from parent class, it sends init message to super class that is NSObject. And does no initialization, it simply return self (NSObject). Because Fraction inherited from NSObject,
Why I should not do this?
- (id)init {
self = [self init]; // Inherited class can use parent method (init)
if (self) {
// Initialize self.
}
return self;
}
What does init method actually do?