English 中文(简体)
目标C:
原标题:Objective C init

否认,我对目标C来说是新的,但我无法找到解释。 我看到了两种执行方式:

- (id)init {

  if ([super init]) {
    return self;
  } else {
    return nil;
  }

}

以及

- (id)init {
    if (self = [super init]) {
      // do your init business here
    } 
    return self;
}

因此,我要说:

myObj = [[MyObject alloc] init];

在MyObject上课是NSObject的子类。 在第二个例子中,是否未归还最初版本的NSObject? 那么,我Obj会知道什么? 它是否认为它是国家科学学会的目标,而不是我的目标?

问题回答

(1) 第一版是错误的。 www.un.org/spanish/ecosoc 应以<代码>super 初始代用人回归,因为init<...>super可在初始化时返还另一个物体(并非异常的BTW)。 第二版实际上是实施<条码>init<......>方法的正式途径。

(2) 它认为它是国家科学学会的目标,而不是我的目标。 MyObj is,in NSObject ande of MyObject . 它是整个继承点。

i 仅想知道,在一生中,它是如何做到的。

这很简单。 在所有班次中,有99.9%的人将用某种方式继承。 在初始设计者中,您应援引<代码>super指定初始设计人,并将其指定为<代码>自封/代码>。 最终,[super init]将援引-[NSObject init] 根据号文件,执行如下:

- (id)init {
    return self;
}

因此,如果你直接从<代码>NSObject继承,你或许可以安全而不必指定<代码>本身 = [超级 init];,因为你知道(和你再次保证)这相当于:<代码>自封;,这是无意义的。 不管怎样,你为了一致性而离开。

However, once you start getting further down the inheritance chain, and especially when you re inheriting from opaque classes (ie, a class whose .m file you do not have), then things start getting shady. It is possible that you ll come across a class whose designated initializer looks something like this:

- (id) initWithFoo:(id)aFoo {
  if ([aFoo isSuperFast]) {
    [self release];
    return [[SuperFastFooWrapper alloc] initWithFoo:aFoo];
  }
  self = [super init];
  if (self) {
    _foo = [aFoo retain];
  }
}

这是常见的,但确实发生。 在这种情况下,我们重新销毁了<代码>本身([自发布],以平衡紧随其后的<代码>alloc呼号”,而是退回了另一个物体。





相关问题
Subclass check, is operator or enum check

A couple of friends was discussing the use of inheritance and how to check if a subclass is of a specific type and we decided to post it here on Stack. The debate was about if you should implement a ...

C++ Class Inheritance problem

Hi I have two classes, one called Instruction, one called LDI which inherits from instruction class. class Instruction{ protected: string name; int value; public: Instruction(string ...

Overloading a method in a subclass in C++

Suppose I have some code like this: class Base { public: virtual int Foo(int) = 0; }; class Derived : public Base { public: int Foo(int); virtual double Foo(double) = 0; }; ...

Embedding instead of inheritance in Go

What is your opinion of this design decision? What advantages does it have and what disadvantages? Links: Embedding description

Extending Flex FileReference class to contain another property

I want to extend the FileReference class of Flex to contain a custom property. I want to do this because AS3 doesn t let me pass arguments to functions through event listeners, which makes me feel sad,...

Interface Inheritance in C++

I have the following class structure: class InterfaceA { virtual void methodA =0; } class ClassA : public InterfaceA { void methodA(); } class InterfaceB : public InterfaceA { virtual ...

热门标签