要为UITableViewController子类覆盖哪个初始化程序 [英] Which initializer(s) to override for UITableViewController subclass
问题描述
我有一个 UITableViewController
子类实例化,取决于它的使用,在NIB或通过代码。在这两种情况下,我想在initializer方法中进行自定义。这是否意味着我需要实现 initWithNibName:bundle:
和 initWithCoder:
每个方法都会调用它各自的超级初始化器?
I have a UITableViewController
subclass that's instantiated, depending on where it's used, in a NIB or via code. In both cases I want to do customization in the initializer method. Does that mean I need to implement both initWithNibName:bundle:
and initWithCoder:
, and would each method call its respective super initializer?
虽然我现在不需要这个,但如果我也想要能够实例化视图控制器 initWithStyle:
?然后我需要3个不同的init方法来复制相同的行为吗?
While I don't need this right now, what if I also want to be able to instantiate the view controller with initWithStyle:
? Would I then need 3 different init methods that replicate the same behavior?
看起来这违反了整个指定的初始化器约定,因为本质上有3个单独的初始化器最后调用一个公共的init方法。
It seems like this violates the whole designated initializer convention, as there would essentially be 3 separate initializers that don't end up calling a common init method. Or is there a way to create a common designated initializer while supporting the 3 different instantiate routes?
推荐答案
我的困惑是基于以下两个原因:错误地认为每个类应该有一个指定的初始化器。这不是真的,在 UITableViewController
的情况下有3个指定的初始化器(据我所知):
My confusion was based on the mistaken belief that each class should have a single designated initializer. This is not true, and in the case of UITableViewController
there are 3 designated initializers (as far as I can tell):
-
initWithStyle:
本地声明 -
initWithNibName:bundle: code>继承自
UIViewController
-
initWithCoder:
code> NSCoding 协议
initWithStyle:
declared locallyinitWithNibName:bundle:
inherited fromUIViewController
initWithCoder:
from adoptingNSCoding
protocol
您需要覆盖1个 ,取决于您的子类实例化的方式。在我的情况下,我不得不实现#2和#3,因为类可以从NIB加载,或通过参考NIB的代码实例化。 (我想,对于单个类,你很少会使用 initWithStyle:
和 initWithNibName:bundle:
)。
You need to override 1 or more of these in your subclass depending on how your subclass gets instantiated. In my case I had to implement #2 and #3 since the class can be loaded from a NIB, or instantiated via code with reference to a NIB. (I imagine it's rare that you'll use both initWithStyle:
and initWithNibName:bundle:
for a single class.)
我发现苹果 Cocoa的编码指南 有用。
I found Apple's Coding Guidelines for Cocoa helpful.
这篇关于要为UITableViewController子类覆盖哪个初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!