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

Say I have a class called Item. What is the superclass of NewsItem and TwitterItem.

If I want to create some NewsItem, I have to use (inside the constructor)

self = [super init]; 

If so, why? In Java / C #, I would just do

  NewsItem n = new NewsItem(); 

I don't need to do anything with superclasses in Java / C #. I just can’t understand this.

+1
source share
4 answers

In Java and C #, the compiler automatically forces your constructor to call the constructor of the superclass, unless you explicitly name it. For example, Java Tutorials says this :

If the constructor does not explicitly call the constructor of the superclass, the Java compiler automatically inserts a call to the constructor without arguments to the superclass. If the superclass does not have a constructor with no arguments, you will get a compile-time error. An object has such a constructor, so if Object is the only superclass, there is no problem.

In Objective-C, the compiler does not do this automatically, so you need to do it yourself.

+6
source

Because your superclass (and your superclass of the superclass class) also needs to be initialized.

And remember that your superclass will [rarely] return zero or another instance.

This is why you do:

 - (id)init { self = [super init]; if (self) { ... init stuff .... } return self; } 
+5
source

Because you are redefining the init message. If you do not override it, then [[NewsItem alloc] init] will simply cause a message to initialize the superclass. In C #, you can use base to do the same.

+1
source

since your custom object at least inherits from the mothers of all objects: NSObject, you must call '[super init];' "super" just calls the init method of its superclass

0
source

Source: https://habr.com/ru/post/924546/


All Articles