objective-ciosautoreleasedealloc

autorelease vs. release in dealloc


I know memory management in iOS is tricky subject to newbies like me, but I was hoping for a clear explanation here on stackoverflow which I could not find anywhere else.

So, pretend I have a property / ivar

@property(nonatomic, retain) UIPopoverController *popOver;

which I'm allocating like this:

self.popOver = [[[UIPopoverController alloc] initWithContentViewController:popOverContent] autorelease];    

Now, in my dealloc and viewDidUnload methods, I do both

// in viewDidUnload:
self.popOver = nil;
// in dealloc:
[popOver release];

Question:

  1. If I do nil / release in viewDidUnload / dealloc, do I really need to autorelease at allocation?
  2. Vice versa, if I do autorelease at allocation, do I need to nil / release later?
  3. What's the difference, if any?

Thanks in advance for your time - I'll continue reading, seriously memory management can't be that hard to wrap your head around...


Solution

  • Don't be confused by the autorelease in this line:

    self.popOver = [[[UIPopoverController alloc] initWithContentViewController:popOverContent] autorelease];
    

    After this statement you effectively own the object because the property setter claimed ownership of it. The autorelease balances the alloc-init.

    So... yes, you need to autorelease at allocation. If you did this (no autorelease), you would leak:

    self.popOver = [[UIPopoverController alloc] initWithContentViewController:popOverContent];
    

    Another option is to use a temporary variable instead of autorelease:

    UIPopoverController *temp = [[UIPopoverController alloc] initWithContentViewController:popOverContent];
    self.popOver = temp;
    [temp release];
    

    Either way you need to release the object in dealloc.