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?
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.
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.
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.
The code is incorrect. You'll end up releasing imgView
after it's been deallocated.
In your .m file, you:
alloc
it --> you own itrelease
it --> you don't own itThen 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With