morgancodes
morgancodes

Reputation: 25285

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?

Upvotes: 3

Views: 3319

Answers (3)

wattson12
wattson12

Reputation: 11174

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

Upvotes: 4

touti
touti

Reputation: 1164

yes the "init" default constructor don't do a spécifique processing
because the init method defined in the NSObject class does no initialization; it simply returns self.

Upvotes: 0

Joe
Joe

Reputation: 57179

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.

Upvotes: 1

Related Questions