Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

objective c - alloc and init what do they actually do

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • alloc allocates a chunk of memory to hold the object, and returns the pointer.

    MyClass* myObj = [MyClass alloc];
    

    myObj cannot be used yet, because its internal state is not correctly setup. So, don't write a code like this.

  • init sets up the initial condition of the object and returns it. Note that what's returned by [a init] might be different from a. That explains the code Yannick wrote:

    -init{
         self=[super init]; // 1.
         if(self){          // 2.
             ....
         }
         return self;       // 3.
    }
    
    1. First, you need to call the superclass's init, to setup the superclass's instance variables, etc. That might return something not equal to the original self, so you need to assign what's returned to self.
    2. If self is 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 to nil (if it's object) and 0 if it's integer. You'll need to perform additional initial settings.
    3. Return the set-up self. The returned self might be different from what's allocated! So, you need to assign the result of init to your variable.

This suggestions an important lesson: never split the call to alloc and init. Don't write:

 MyClass* myObj = [MyClass alloc];
 [myObj init];

because [myObj init] might return something else. Don't try to get around this by writing:

 MyClass* myObj = [MyClass alloc];
 myObj=[myObj init];

because you will eventually forget to write the part myObj= in the second line.

Always write:

 MyClass* myObj = [[MyClass alloc] init];

I also don't recommend writing:

 MyClass* myObj = [MyClass new];

because it does not correctly call the initialization method: some classes doesn't accept a plain init. For example, NSView needs initWithFrame:, which can't be called with new. So, don't use new either.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...