Objective C 是否需要 init()
Is init() needed in Objective C
我是 Objective C 的新手。我无法理解 init() 方法。我在 Apple 网站上看过这两行:
NSObject中定义的init()方法class没有初始化;它只是 returns 自我。 (https://developer.apple.com/reference/objectivec/nsobject/1418641-init)
您必须使用 init... 方法来完成初始化过程。 (https://developer.apple.com/reference/objectivec/nsobject/1571958-alloc)
"it does no initialization"是否需要调用init()来初始化对象?为什么?
来自 Apple Developer on Object Initialization :
If an object does not implement an initializer, Cocoa invokes the
initializer of the nearest ancestor instead.
是的,您需要调用某种形式的 init 在 heap. The init returns a point to the memory location. No, you don't need to write an init 上为您的自定义对象创建您的对象 ,除非默认的全部归零初始化不充分.
当使用 +alloc
创建实例对象时,它会获得完全设置的基础结构,并且所有 ivar 都设置为 0
、NULL
、nil
, 0.0
(或 ivar 类型的零值)。
如果这对 class 来说足够了,就没有必要覆盖 -init
,它可以简单地使用 NSObject
s init。 (NSObject
的 -init
什么都不做。)这是 实现者的 方面。这就是您在 1).
中所指的内容
class 的 user (创建实例的代码)必须将 init
发送给新创建的实例以提供给它机会 初始化自身。这就是你在 2) 中提到的内容。
作为 class 的用户,您根本无法知道也不应该知道 class 在其初始化过程中是否需要一些代码。所以发送消息,即使它可能没用。
我是 Objective C 的新手。我无法理解 init() 方法。我在 Apple 网站上看过这两行:
NSObject中定义的init()方法class没有初始化;它只是 returns 自我。 (https://developer.apple.com/reference/objectivec/nsobject/1418641-init)
您必须使用 init... 方法来完成初始化过程。 (https://developer.apple.com/reference/objectivec/nsobject/1571958-alloc)
"it does no initialization"是否需要调用init()来初始化对象?为什么?
来自 Apple Developer on Object Initialization :
If an object does not implement an initializer, Cocoa invokes the initializer of the nearest ancestor instead.
是的,您需要调用某种形式的 init 在 heap. The init returns a point to the memory location. No, you don't need to write an init 上为您的自定义对象创建您的对象 ,除非默认的全部归零初始化不充分.
当使用 +alloc
创建实例对象时,它会获得完全设置的基础结构,并且所有 ivar 都设置为 0
、NULL
、nil
, 0.0
(或 ivar 类型的零值)。
如果这对 class 来说足够了,就没有必要覆盖 -init
,它可以简单地使用 NSObject
s init。 (NSObject
的 -init
什么都不做。)这是 实现者的 方面。这就是您在 1).
class 的 user (创建实例的代码)必须将 init
发送给新创建的实例以提供给它机会 初始化自身。这就是你在 2) 中提到的内容。
作为 class 的用户,您根本无法知道也不应该知道 class 在其初始化过程中是否需要一些代码。所以发送消息,即使它可能没用。