Objective C - init 和构造函数之间的区别?
我试图找到 Objective CI 中 init 和构造函数之间的区别,我不是 C 开发人员,但我需要将一些 Objective C 代码转换为 Java,实际上我无法理解两者之间的区别。
I'm trying to find the difference between init and constructor in Objective C.I'm not a C developer, but I need to convert some Objective C-code to Java and actually I can't understand the difference between both things.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 Objective-C 中,对象的生成方式分为两部分:分配和初始化。
您首先为对象分配内存,该对象会被零填充(除了一些您不需要关心的 Objective-C 内部内容):
下一阶段是初始化。按照惯例,这是通过以
init
开头的方法来完成的。由于各种原因(尤其是在使用 ARC 时),您应该遵守此约定,但从语言的角度来看没有必要。或一行:
在其他语言中,这些
init
方法称为构造函数,但在 Objective-C 中,并不强制要求在分配对象时调用“构造函数” 。您有责任调用适当的init
方法。在 C++、C# 和 Java 等语言中,分配和初始化紧密耦合,以至于您无法在不初始化对象的情况下分配对象。简而言之:
init
方法可以被视为构造函数,但仅通过命名约定而不是语言强制执行。对于 Objective-C 来说,它们只是普通的方法。In Objective-C, the way an object comes to life is split into two parts: allocation and initialization.
You first allocate memory for your object, which gets filled with zeros (except for some Objective-C internal stuff about which you don't need to care):
The next stage is initialization. This is done through a method that starts with
init
by convention. You should stick to this convention for various reasons (especially when using ARC), but from a language point of view there's no need to.or in one line:
In other languages these
init
methods are called constructors, but in Objective-C it is not enforced that the "constructor" is called when the object is allocated. It's your duty to call the appropriateinit
method. In languages like C++, C# and Java the allocation and initialization are so tightly coupled that you cannot allocate an object without also initializing it.So in short: the
init
methods can be considered to be constructors, but only by naming convention and not language enforcement. To Objective-C, they're just normal methods.