要为UITableViewController子类覆盖哪个初始化程序 [英] Which initializer(s) to override for UITableViewController subclass

查看:178
本文介绍了要为UITableViewController子类覆盖哪个初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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):


  1. initWithStyle:本地声明

  2. initWithNibName:bundle: code>继承自 UIViewController

  3. initWithCoder: code> NSCoding 协议

  1. initWithStyle: declared locally
  2. initWithNibName:bundle: inherited from UIViewController
  3. initWithCoder: from adopting NSCoding 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆