xonegirlz
xonegirlz

Reputation: 8967

custom init method in objective-C

If I am writing my own custom init method what would I call be the appropriate call to super init be? I sometimes see it's not just some super init method but something else, what's the general rule for this?

Upvotes: 0

Views: 573

Answers (4)

AndersK
AndersK

Reputation: 36082

The general rule is you should call [super init] when you initialize your class. That way the init method of the class you inherit of (typically NSObject) will also be called and thus constructed. If all classes follow this rule a chain of inits will be established.

Same rule goes in dealloc, there you call the [super dealloc].

Upvotes: 0

pgb
pgb

Reputation: 25001

Objective-C classes may have multiple init methods. Usually, one of them is called the "Designated Initializer", and is the one all the rest call.

If you are subclassing, and creating an init method with a different signature, you should call the superclass' designated initializer (although calling any initializer of the superclass will work as well). The documentation for the classes will usually tell you what the designated initializer is.

For instance, in UITableViewCell the designated initializer is initWithStyle:reuseIdentifier: and is the one you should call if you subclass and create an init method with a different signature.

Upvotes: 2

Oliver
Oliver

Reputation: 23510

Building your own init method, you should call super init, or if your object is associated with a xib, you could also call super initWithNibName:bundle: as a shorcut to force the one that implement your object to use one and only one xib. In that last case, you should also overload initWithNibName:bundle: to make the same force call in case the caller uses it.

If your object is included in a XIB, also overload initWithCoder

Upvotes: 0

Mellson
Mellson

Reputation: 2948

It depends on the context, try to put in some nslogs and see which init is called for you. If it is [super init] or something like initWithNib...

Upvotes: 0

Related Questions