Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone Memory Management and Releasing

Here's a common practice I see often (including from a very popular iPhone developer book)

In the .h file:

@interface SomeViewController : UIViewController
{
  UIImageView *imgView;
}

Somewhere in the .m file:

imgView = [[UIImageView alloc] initWithFrame:[[UIScreen mainScreen]
applicationFrame]];
[imgView setImage:[UIImage imageNamed:@"someimage.png"]];
[self addSubview:imgView];
[imgView release];

And later, we see this...

- (void) dealloc
{
  [imgView release];
  [super dealloc];

} 

Since imgView has a matching alloc and release, is the release of imgView in dealloc necessary?

Where is the imgView retained by the addSubview call accounted for?

like image 459
John Muchow Avatar asked May 05 '09 02:05

John Muchow


People also ask

How does memory management work on iOS?

Memory management in iOS was initially non-ARC (Automatic Reference Counting), where we have to retain and release the objects. Now, it supports ARC and we don't have to retain and release the objects. Xcode takes care of the job automatically in compile time.

Why iOS has better RAM management?

Whereas Android memory is handled by the operating system, iOS memory is handled by the apps themselves. Instead of allowing apps to take up as much RAM as they want and freeing it when no longer in use, iOS apps automatically allocate and de-allocate memory as needed.

What is memory management in iOS Swift?

Swift uses Automatic Reference Counting (ARC) to track and manage your app's memory usage. In most cases, this means that memory management “just works” in Swift, and you don't need to think about memory management yourself.


1 Answers

The code is incorrect. You'll end up releasing imgView after it's been deallocated.

In your .m file, you:

  1. alloc it --> you own it
  2. add it as a subview --> you and the UIView owns it
  3. release it --> you don't own it

Then in dealloc, you release imgView even though, as we established at step 3 above, you don't own it. When you call [super dealloc], the view will release all of its subviews, and I imagine you'll get an exception.

If you want to keep an ivar of imgView, I suggest not calling release after you add it as a subview, and keep your dealloc the same. That way, even if imgView is at some point removed from the view hierarchy, you'll still have a valid reference to it.

like image 85
Daniel Dickison Avatar answered Sep 22 '22 10:09

Daniel Dickison