NB: To clarify what I’m trying to do here:
I have an instance of a subclass of UIView. When this instance gets released from a View Controller I would like that the dealloc method of that instance be called.
The point being to release other objects within that instance of the subclass of UIView.
In the View Controller:
- (void)viewDidLoad
{
[super viewDidLoad];
self.mav = [[MapAreaView alloc]init];
[self.view addSubview:self.mav];
[self.mav release];
t_ = [NSTimer scheduledTimerWithTimeInterval: 20.0f target: self selector:@selector(onTick) userInfo: nil repeats:NO];
}
and:
- (void)onTick
{
NSLog(@"Releasing...");
[t_ invalidate];
t_ = nil;
[self.mav release];
[self.mav release];
[self.mav release];
NSLog(@"Done releasing.");
}
In MapAreaView:
- (void)dealloc
{
NSLog(@"map view area dealloc called.");
[super dealloc];
}
I am trying to release the MapAreaView and have it’s dealloc method called.
Also, when I run this app, Releasing... and Done releasing. get printed, but not map view area dealloc called. And despite all of my excessive release messages sent to self.mav the app doesn’t crash. Weird.
Ideas?
EDIT 1
@interface MemoryManagmentViewController : UIViewController {
MapAreaView *mav_;
NSTimer *t_;
}
@property (nonatomic, retain) MapAreaView *mav;
which is then synthesized: @synthesize mav = mav_;
EDIT 2
Please not that the timer is not for use in my real application. I’m just using it to learn about memory management.
First off, don’t use
[self.mav release]. This is incorrect use of properties, and is not guaranteed to release your object. Useself.mav = nilinstead.Secondly, I presume your crazy timer is there just to try and force the release of your view and isn’t really code you are using? Because it really shouldn’t be there!
To manage the memory of a view that you want to both keep a pointer to and add as a subview to your main view, remove the release and timer messages from your viewDidLoad. You now have one retained pointer to
mav, via your property, and the view will be retaining it as well since it is a subview.In viewDidUnload, your view no longer exists so it will no longer have a pointer to
mav. Therefore, if you putself.mav = nilthere,mavwill be released.You shouldnt try to release it while it is still a subview of another view.