简体   繁体   中英

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?

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.

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...

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

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] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM