Can someone explain to me what init and alloc do in Obj-C. I am reading this obj-c book that gives an example of creating object but it does not really go into details of what it does. What does alloc return? what does init return?
Animal * k = [Animal alloc];
k = [k init];
allocallocates a chunk of memory to hold the object, and returns the pointer.myObjcannot be used yet, because its internal state is not correctly setup. So, don’t write a code like this.initsets up the initial condition of the object and returns it. Note that what’s returned by[a init]might be different froma. That explains the code Yannick wrote:init, to setup the superclass’s instance variables, etc. That might return something not equal to the originalself, so you need to assign what’s returned toself.selfis non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set tonil(if it’s object) and0if it’s integer. You’ll need to perform additional initial settings.self. The returnedselfmight be different from what’s allocated! So, you need to assign the result ofinitto your variable.This suggestions an important lesson: never split the call to
allocandinit. Don’t write:because
[myObj init]might return something else. Don’t try to get around this by writing:because you will eventually forget to write the part
myObj=in the second line.Always write:
I also don’t recommend writing:
because it does not correctly call the initialization method: some classes doesn’t accept a plain
init. For example,NSViewneedsinitWithFrame:, which can’t be called withnew. So, don’t useneweither.