Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding init in subclass

In Objective-C, is it necessary to override all inherited constructors of a subclass to add custom initialization logic?

For example, would the following be correct for a UIView subclass with custom initialization logic?

@implementation CustomUIView  - (id)init {     self = [super init];     if (self) {         [self initHelper];     }     return self; }  - (id)initWithFrame:(CGRect)theFrame {     self = [super initWithFrame:theFrame];     if (self) {         [self initHelper];     }     return self; }  - (id)initWithCoder:(NSCoder *)decoder {     self = [super initWithCoder:decoder];     if (self) {         [self initHelper];     }     return self; }  - (void) initHelper {     // Custom initialization }  @end 
like image 435
hpique Avatar asked Dec 05 '10 15:12

hpique


People also ask

Can you override __ init __?

Answer #5: Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

How do you override a subclass in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

What does super () __ Init__ do?

Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.


2 Answers

Every Cocoa Touch (and Cocoa) class has a designated initializer; for UIView, as stated in this documentation, that method is initWithFrame:. In this particular case, you'll only need to override initWithFrame; all other calls will cascade down and hit this method, eventually.

This goes beyond the scope of the question, but if you do end up creating a custom initializer with extra parameters, you should make sure to the designated initializer for the superclass when assigning self, like this:

- (id)initWithFrame:(CGRect)theFrame puzzle:(Puzzle *)thePuzzle title:(NSString *)theTitle {     self = [super initWithFrame:theFrame];     if (self) {         [self setPuzzle:thePuzzle];         [self setTitle:theTitle];         [self initHelper];     }     return self; } 
like image 72
Sam Ritchie Avatar answered Sep 21 '22 18:09

Sam Ritchie


In case of using Interface Builder, the one is called is :

- (id)initWithCoder:(NSCoder *)coder {     self = [super initWithCoder:coder];     if (self) {        //do sth     }     return self; } 
like image 42
letanthang Avatar answered Sep 21 '22 18:09

letanthang