Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...

like image 860
pille Avatar asked Sep 03 '11 13:09

pille


People also ask

What does Autorelease mean?

Filters. (computing) Automatic release (of previously allocated resources)

Which of the following do you use to deallocate memory free () Dalloc () Dealloc () Release ()?

Realloc() If you need to reallocate a memory block, you can use the realloc() function… void* realloc (void* ptr, size_t size);

What is Dealloc in C?

-dealloc is an Objective-C selector that is sent by the Objective-C runtime to an object when the object is no longer owned by any part of the application. -release is the selector you send to an object to indicate that you are relinquishing ownership of that object.

Does Objective-C have memory management?

Objective-C provides two methods of application memory management. In the method described in this guide, referred to as “manual retain-release” or MRR, you explicitly manage memory by keeping track of objects you own.


1 Answers

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.

like image 101
albertamg Avatar answered Oct 16 '22 19:10

albertamg