对象初始化为什么[super init]不是[self init]

时间:2014-06-01 09:43:18

标签: objective-c

要完成该对象,需要执行这些步骤。

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.

问题:


我写了一个课

@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);
}

在main.m

Fraction *fraction = [Fraction alloc]; // without the initialization
fraction.denominator = 3;
[fraction print];

这是我在控制台上获得的

0/3

1)分子的值为0.我没有设置分子并打印0.这很奇怪,因为整数默认值应该是未定义的。怎么会发生这种情况?

2)使用alloc,所有实例变量的内存都设置为0.但是,如何将分母设置为3,它仍然有效。要将值存储到denominator(int)变量,我们需要分配4个字节的内存。

3)最后一个问题,当我做

- (id)init {
    self = [super init];
    if (self) {
        // Initialize self.
    }
    return self;
}

init方法继承自父类,它将init消息发送给NSObject的超类。并且没有初始化,它只是返回self(NSObject)。 因为Fraction继承自NSObject,

为什么我不应该这样做?

- (id)init {
    self = [self init]; // Inherited class can use parent method (init)
    if (self) {
        // Initialize self.
    }
    return self;
}

init方法实际上做了什么?

1 个答案:

答案 0 :(得分:2)

答案实际上很简单:

self = [self init];

是一个导致堆栈溢出的无限递归:

Stack overflow

一般而言,one should avoid using self for accessing methods of partially constructed or partially destructed objects.