Search code examples
macoscocoainitalloc

Alloc and init in Cocoa


Maybe this is a dumb question, but I really want to figure this one out.

For example I have the following setup:

// .h
@interface MyClass : NSObject
{
   NSView *myView;
}

// .m

@implementation MyClass

-(void)someMethod
{

   // WHAT IS THE DIFFERENCE BETWEEN THIS
   myView = [[NSView alloc] init];

   // AND THIS ?

   myView = [myView init]; // assuming that myView was allocated somewhere earlier in init method
}

Solution

  • init methods tend to assume that you only send init once to every object.

    Sending init again to a previously-allocated-and-initialized myView will break this assumption, causing memory leaks and possibly subsequent weird behavior. Both result from your second init message to myView creating objects, adding observers, etc. that the same object had already set up before.

    That's what the second line in someMethod does.

    The first line creates a new view, this being the impact of the alloc/init one-two punch. This view is a different object from the view you entered someMethod with (if any), so sending init to that object as part of its creation is not a problem.

    Remember: the object is not the variable. myView is the name of the variable; when we say “myView”, we really mean “the object that myView holds”.

    (It may be a good idea to re-read this answer from the top with the concept from the last paragraph firmly in mind.)