Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSObject init always called?

In Cocoa, it's recommended to always called the superclass's designated initializer. Is it safe to assume that init will always be called, during an object's initialization, even if the object isn't initialized with init?

For example, if let's say there's a class: NSThingie, which can be initialized like [[NSThingie alloc] initWithFoo: foo], or [[NSThingie alloc] initWithFoo: foo andBar: bar]. If I override init, can I assume that it will be called at some point during initialization?


EDIT

Maybe my original question wasn't worded so well. I know that overriding init causes init in superclasses to not be called, and I must explicitly call init. What I'm wondering is whether, in the apple frameworks, [NSObject init] is always called. If I initialize some Apple object like [[NSAppleClass alloc] initWithSomething: something], can I assume that NSObject's init will eventually be called during the initialization of NSAppleClass?

like image 835
morgancodes Avatar asked Dec 05 '25 10:12

morgancodes


2 Answers

short answer: no

you need to make sure you are overriding the correct init method for the class you are using

for example UIView has an init method initWithFrame: and a very basic implementation of that would be:

- (id)initWithFrame:(CGRect)frame
{
    self = [super init]; //calls init because UIResponder has no custom init methods
    if (self){
        self.frame = frame;
    }
    return self;
}

init is called on the superclass, but not on UIView, so if you were to override init and not initWithFrame: your initialisation code would never be run

like image 165
wattson12 Avatar answered Dec 08 '25 22:12

wattson12


If I override init, can I assume that it will be called at some point during initialization?

If you override and init method you are responsible for calling the designated initializer. It is the responsibility of the developer to call correct initializer of the class that is subclassing. The reason you call the designated initializer is to make sure the class is constructed in its intended state. Not calling the correct initializer or not calling an initializer at all will likely result in undefined/undesirable behavior.

like image 37
Joe Avatar answered Dec 08 '25 23:12

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!