1

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)

    self = [super init];

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

    NewsItem n = new NewsItem();

I don't have to do anything with superclasses in Java/C#. Just can't grasp it.

xrDDDD
  • 583
  • 9
  • 23
  • 1
    possible duplicate of [Why should I call self=\[super init\]](http://stackoverflow.com/questions/2956943/why-should-i-call-self-super-init) – jscs Feb 14 '12 at 19:43

4 Answers4

6

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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
5

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;
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
bbum
  • 162,346
  • 23
  • 271
  • 359
  • Kevin added the return type. Thanks. Not strictly necessary as (id) is the default, but I prefer it, too. – bbum Feb 14 '12 at 22:57
1

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.

NJones
  • 27,139
  • 8
  • 70
  • 88
typeoneerror
  • 55,990
  • 32
  • 132
  • 223
0

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

pmk
  • 1,897
  • 2
  • 21
  • 34