Why to use [super init] in Objective C constructors?

前端 未结 4 1943
面向向阳花
面向向阳花 2021-01-24 14:34

Say I have a class named Item. Which is a superclass of NewsItem and TwitterItem.

If I want to create some NewsItem\'s do I have to use (inside constructor)

<         


        
相关标签:
4条回答
  • 2021-01-24 14:44

    Because your superclass (and your superclass's superclass) need a chance to initialize, too.

    And, keep in mind, that your superclass will [rarely] return nil or a different instance.

    Which is why you do:

    - (id)init
    {
        self = [super init];
        if (self) {
            ... init stuff ....
        }
        return self;
    }
    
    0 讨论(0)
  • 2021-01-24 14:46

    In Java and C#, the compiler automatically makes your constructor call the superclass constructor if you don't explicitly call it. For example, the “Java Tutorials” say this:

    If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error. Object does have such a constructor, so if Object is the only superclass, there is no problem.

    In Objective-C, the compiler doesn't do it automatically, so you have to do it yourself.

    0 讨论(0)
  • 2021-01-24 14:49

    since your custom object will at least inherit from the mothers of all Objects: NSObject, you have to call '[super init];' 'super' simply does call the init Method of its superclass

    0 讨论(0)
  • 2021-01-24 15:00

    Because you are overriding the init message. If you don't override it then [[NewsItem alloc] init] would just call the superclass' init message. In C#, you might use base to do the same.

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