potential memory leak

Discussion in 'Mac Programming' started by BollywooD, Jan 12, 2010.

  1. BollywooD macrumors 6502


    Apr 27, 2005
    I thought i had memory management all figured out, but I have this line of code:
    [subscriptionTable setDataSource:[[subscriptionsDS alloc] initWithSubscriptions:[self subscriptions]]];
    which I am not quite sure how to release, i tried this:

    [subscriptionTable setDataSource:[[[subscriptionsDS alloc] initWithSubscriptions:[self subscriptions]]  autorelease]]
    but this causes a crash...

    .....subscriptionsDS is a class, how do I release a class?.....
    <edit>how do I release an NSTableView, I have created programatically?</edit>
  2. larkost macrumors 6502a

    Oct 13, 2007
    You are not alloc'ing the class, but rather telling the class to alloc (reserve some memory for you), and then with the initWithSubscriptions command telling it to put a instance in that space. The latter part is a bit of trickery if you really think about where messages are going, but that is how it works.

    Then you are doing a second thing, namely telling subscriptionTable (an object) to set its data source to the class you just alloc'ed/init'ed. From there the memory management gets a bit murky, because we don't know that subscriptionTable is (it might be taking over the memory management, or it might not).
  3. Sydde macrumors 68020


    Aug 17, 2009
    It causes a crash because the datasource gets released, then subscriptionTable tries to call it. You do not want to release a datasource, it should stick around.

    +alloc is a class method that creates an object instance of a class. Generally speaking, you would not release a class.

    So, you really should not be releasing the subscriptionDS object at all. As long as the table wants to use the datasource, the object should exist, or you will have a crash. If you need to release it later, you could send

    at some point before you release the table. Without Garbage Collection, NSTableView does not retain the datasource (it is what is called a "weak reference"), so you would have to do that yourself.

    It does often help to break your code into multiple lines rather than creating deep nests of methods. The compiler seems to be very good at optimizing code.
  4. Sydde macrumors 68020


    Aug 17, 2009
    One way to release a tableview would be

    [subscriptionTable removeFromSuperview];
    That will cause its superview to release it - but as I said above, you should probably release the dataSource just prior to doing that.

Share This Page