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?
Yes, that code has problems. It
releases the imgView too early which could potentially cause crashes in rare circumstancesstores an object in an instance variable without retaining it, and it’s just generally going about memory management the wrong way.One correct way to do this would be:
And in the implementation;
Somewhere in the module:
And the dealloc remains the same: