Objective C - init 和构造函数之间的区别?

发布于 2024-12-02 01:29:59 字数 102 浏览 2 评论 0原文

我试图找到 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半暖夏伤 2024-12-09 01:29:59

在 Objective-C 中,对象的生成方式分为两部分:分配初始化

您首先为对象分配内存,该对象会被零填充(除了一些您不需要关心的 Objective-C 内部内容):

myUninitializedObjectPointer = [MyClass alloc];

下一阶段是初始化。按照惯例,这是通过以 init 开头的方法来完成的。由于各种原因(尤其是在使用 ARC 时),您应该遵守此约定,但从语言的角度来看没有必要。

myObjectPointer = [myUnitializedObjectPointer init];

或一行:

myObjectPointer = [[MyClass alloc] init];

在其他语言中,这些 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):

myUninitializedObjectPointer = [MyClass alloc];

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.

myObjectPointer = [myUnitializedObjectPointer init];

or in one line:

myObjectPointer = [[MyClass alloc] init];

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 appropriate init 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文