gpt4 book ai didi

iphone - 关于覆盖 init 函数的几个问题

转载 作者:搜寻专家 更新时间:2023-10-30 19:55:33 25 4
gpt4 key购买 nike

作为 Objective-C 初学者,我对 init 函数以及如何以及何时覆盖它感到非常困惑。所以这里有几个问题:

  • 显然,当 init 函数未被覆盖时它工作正常,那么这样做只是一个好习惯吗?如果是,那么不这样做是不是一种非常糟糕的做法?
  • 假设我正在覆盖该函数,因为我必须为变量分配一个默认值。我是否必须分配和初始化所有其他 ivar,包括 IBOutlets?

请注意我知道语法:

if ((self = [super init]))
{
_foo = [[Bar alloc] init];
}
return self;

最佳答案

根据 "Initialization" :

A class generally implements an initializer for its objects, but is not required to. If a class does not implement an initializer, Cocoa calls the initializer of the nearest ancestor of the class. However, subclasses often define their own initializer or override an initializer of their superclass to add class-specific initializations. If a class does implement an initializer, it should invoke an initializer of its superclass as the first step. This requirement ensures a series of initializations for an object down the inheritance chain, starting with the root object. The NSObject class declares the init method as the default object initializer, so it is always invoked last but returns first.

如上文所述,当您需要在父类(super class)完成初始化后进行一些初始化时,您可以覆盖父类(super class)的指定初始化程序。不需要那样做?那么你不需要重写。

当您的对象从 NIB 实例化时,-init 不会被调用。相反,您新分配的对象将收到 -initWithCoder:-initWithFrame: 消息,具体取决于对象的类型。 NIB 加载过程在它之后发送您的对象 -awakeFromNib 并且它引用的所有其他 NIB 创建的对象都已建立。当您希望在加载 NIB 后进行一些配置时,这可以让您避免覆盖 -initWithCoder:/-initWithFrame:。如果您可以通过覆盖 -awakeFromNib 而不是初始化程序来做您想做的事情,那么您应该这样做。

另见 "Multiple Initializers" ,它解释了“指定初始化器”的概念以及不同的类如何可以有不同的指定初始化器,以及 "Allocating and Initializing Objects"以获得对 Objective-C 采用的分配和初始化约定的不太友好但更深入的描述。

关于iphone - 关于覆盖 init 函数的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266209/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com