Objective C - difference between init and constructor?

前端 未结 1 1939
半阙折子戏
半阙折子戏 2021-01-04 21:49

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

相关标签:
1条回答
  • 2021-01-04 22:42

    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.

    0 讨论(0)
提交回复
热议问题