0

可能重复:
我为什么要调用 self=[super init]

我一直在阅读一本 Objective C 的书,并创建一个包含其他类(组合)的类,它使用 self = [super init]

- (id) init
{
    if (self = [super init]) {
        engine = [Engine new];

        tires[0] = [Tire new];
        tires[1] = [Tire new];
        tires[2] = [Tire new];
        tires[3] = [Tire new];
    }

    return (self);

} // init

当他创建另一个类时,他不包含此 init 方法,我知道它需要初始化它将使用的实例对象,但我不明白他为什么要放置 self = [super init] 以及何时一个类需要这个声明。

@interface Tire : NSObject
@end // Tire


@implementation Tire

- (NSString *) description
{
    return (@"I am a tire. I last a while");
} // description

@end // Tire
4

1 回答 1

0

new是一个类方法,它简单地告诉一个类对自己执行 alloc / init。它记录在这里。上面的代码可以重写为:

- (id) init 
{ 
    if (self = [super init]) { 
        engine = [[Engine alloc] init]; 

        tires[0] = [[Tire alloc] init]; 
        tires[1] = [[Tire alloc] init]; 
        tires[2] = [[Tire alloc] init]; 
        tires[3] = [[Tire alloc] init]; 
    } 

    return (self); 

} 

它会产生完全相同的效果,但需要更多的输入。

在 Engine 和 Tire 类中,它们的 init 方法(如果已实现)将使用self = [super init]. 如果你的类在它的方法中没有做任何特殊的事情init,你不需要实现一个,但如果你实现了一个,你必须使用self = [super init],因为你需要正确创建对象,并且你的超类可能正在做重要的工作它的初始化方法。

于 2012-08-01T07:56:13.977 回答