Objective-c: Questions about self = [super init]

前端 未结 8 1155
鱼传尺愫
鱼传尺愫 2020-12-12 23:01


I have seen self = [super init] in init methods. I don\'t understand why. Wouldn\'t [super init] return the superclass? And if we point

相关标签:
8条回答
  • 2020-12-12 23:31

    From Apple's Documentation:

    Because an init... method might return nil or an object other than the one explicitly allocated, it is dangerous to use the instance returned by alloc or allocWithZone: instead of the one returned by the initializer. Consider the following code:

    id myObject = [MyClass alloc];
    [myObject init];
    [myObject doSomething];
    

    The init method in the example above could have returned nil or could have substituted a different object. Because you can send a message to nil without raising an exception, nothing would happen in the former case except (perhaps) a debugging headache. But you should always rely on the initialized instance instead of the “raw” just-allocated one. Therefore, you should nest the allocation message inside the initialization message and test the object returned from the initializer before proceeding.

    id myObject = [[MyClass alloc] init];
    if ( myObject ) {
        [myObject doSomething];
    } else {
        // error recovery... 
    }
    
    0 讨论(0)
  • 2020-12-12 23:33

    Assuming that MyClass is a subclass of BaseClass, the following happens when you call

    MyClass *mc = [[MyClass alloc] init];
    
    1. [MyClass alloc] allocates an instance of MyClass.
    2. The init message is sent to this instance to complete the initialization process.
      In that method, self (which is a hidden argument to all Objective-C methods) is the allocated instance from step 1.
    3. [super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)
    4. In the init method of BaseClass, self is still the same instance of MyClass. This superclass init method can now either

      • Do the base initialization of self and return self, or
      • Discard self and allocate/initialize and return a different object.
    5. Back in the init method of MyClass: self = [super init] is now either

      • The MyClass object that was allocated in step 1, or
      • Something different. (That's why one should check and use this return value.)
    6. The initialization is completed (using the self returned by the superclass init).

    So, if I understood your question correctly, the main point is that

    [super init]
    

    calls the superclass implementation of init with the self argument, which is a MyClass object, not a BaseClass object.

    0 讨论(0)
提交回复
热议问题