Objective C - difference between init and constructor?

那年仲夏 提交于 2019-11-30 18:58:37

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!