简体   繁体   English

objective-C中的自定义init方法

[英]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? 如果我正在编写自己的自定义init方法,我会称之为对super init的适当调用是什么? 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. Objective-C类可能有多个init方法。 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). 如果你是子类,并创建一个具有不同签名的init方法,你应该调用超类的指定初始化程序(尽管调用超类的任何初始化程序也会起作用)。 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. 例如,在UITableViewCell ,指定的初始化程序是initWithStyle:reuseIdentifier:并且如果您子类化并创建具有不同签名的init方法,则应该调用它。

It depends on the context, try to put in some nslogs and see which init is called for you. 它取决于上下文,尝试输入一些nslog并查看为您调用的init。 If it is [super init] or something like initWithNib... 如果它是[super init]或类似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. 构建自己的init方法,你应该调用super init ,或者如果你的对象与xib相关联,你也可以调用super initWithNibName:bundle:作为一个shorcut来强制实现你的对象的那个使用一个且只有一个xib。 In that last case, you should also overload initWithNibName:bundle: to make the same force call in case the caller uses it. 在最后一种情况下,您还应该重载initWithNibName:bundle:以便在调用者使用它时进行相同的强制调用。

If your object is included in a XIB, also overload initWithCoder 如果您的对象包含在XIB中,也会使initWithCoder重载

The general rule is you should call [super init] when you initialize your class. 一般规则是在初始化类时应该调用[super init] That way the init method of the class you inherit of (typically NSObject) will also be called and thus constructed. 这样,您继承的类(通常是NSObject)的init方法也将被调用并因此构造。 If all classes follow this rule a chain of inits will be established. 如果所有类都遵循此规则,则将建立一系列的inits。

Same rule goes in dealloc, there you call the [super dealloc] . 同样的规则在dealloc中,你称之为[super dealloc]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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