Saurabh Bisht
Saurabh Bisht

Reputation: 424

When to Use [Super init] iOS

What is the use of [super init] in Objective-C default methods and what are the condition in which we can use it in our custom methods?

Upvotes: 0

Views: 378

Answers (3)

Amin Negm-Awad
Amin Negm-Awad

Reputation: 16660

To make it short:

A. Every class has one (typically) or more primary (designated) initializers. Before you do your own initialization you have to execute one of the super's primary initializers. For example, in NSObject -init is the primary initializer. If you have a subclass of NSObject you have to execute init (NSObject) before you do your own initialization:

@interface MyClass : NSObject
…
@end

@implementation MyClass
- (id)init // My primary initializer
{
   // Before I do my own -init, if have to execute super's -init
   self = [super init];
   …
}
@end

This holds, if your subclass has a new primary initializer:

@interface MyClass : NSObject
…
@end

@implementation MyClass
- (id)initMyClassWith… // My primary initializer, that's different from NSObject's
{
   // Before I do my own -initMyClass, if have to execute super's -init
   self = [super init]; 
   // As long, as -init is not overridden, self-init would work by acdident, 
   // but you have to override on a PI change, see below!
   …
}
@end

You do not send init to super (more general: execute the PI of super), when you have a convenient initializer. In this case you send the message to self:

@interface MyClass : NSObject
…
@end

@implementation MyClass
- (id)initConvenient // My secondary initializer
{
   self = [self initMyClass]; // primary
   …
}
@end

Therefore on a PI change, you have to override the super's PI to make it execute the subclass' PI:

    @interface MyClass : NSObject
…
@end

@implementation MyClass
- (id)init // subclass' secondary
{
  self = [self initMyClass]; // Primary
   …
}
@end

Upvotes: 1

Nikos M.
Nikos M.

Reputation: 13783

You have to use super init when you are overriding an initializer from your super class. For example if you are subclassing UIViewController, you call [super init] and then you add your custom initialization code.

Upvotes: 0

David Ansermot
David Ansermot

Reputation: 6112

You use [super init] in all subclasses you implement that have also an -init, -initWith... method.

It' to ensure that the parent class code is executed before yours.

Details explanations

Upvotes: 1

Related Questions