本文介绍了目标C - init和constructor之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想在Objective C中找到init和constructor之间的区别。我不是一个C开发人员,但我需要将一些Objective C代码转换为Java,实际上我不能理解两者之间的区别在Objective-C中,对象到达生命的方式分为两部分: allocation 和初始化。 你首先为你的对象分配内存,你不需要关心它): myUninitializedObjectPointer = [MyClass alloc]; 下一阶段是初始化。这是通过按照惯例从 init 开始的方法来完成的。你应该坚持这个约定有各种原因(特别是当使用ARC),但从语言的角度来看,没有必要。 myObjectPointer = [myUnitializedObjectPointer init]; 或在一行中: myObjectPointer = [[MyClass alloc] init]; 在其他语言中,这些 init 构造函数,但在Objective-C中,并不强制在分配对象时调用构造函数。你有责任调用适当的 init 方法。在C ++,C#和Java这样的语言中,分配和初始化非常紧密,你不能在不初始化它的情况下分配对象。 $ c> init 方法可以被认为是构造函数,但只能通过命名约定而不是语言实现。对于Objective-C,它们只是普通的方法。 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. 解决方案 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. 这篇关于目标C - init和constructor之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!