iosmemory-managementviewdidunload

iOS memory management - low memory warnings and viewDidUnload


I'm getting this error when I get a memory warning:

*** -[TheViewController_iPhone productImages]: message sent to deallocated instance

Xcode shows the error being on the line noted below:

- (void)viewDidUnload
{
    [super viewDidUnload];

    [self.productTimer invalidate];
    //self.productTimer = nil;

    for(UIView *subview in [self.productImages subviews]) { //THIS LINE IS THE ERROR
        [subview removeFromSuperview];
    }
}

So my question is, why is productImages (which is a scrollView) deallocated at this point? Shouldn't I get a chance to dump it's subviews?

It is defined like this:

@property (weak, nonatomic) IBOutlet UIScrollView *productImages;

Solution

  • Your view controller's view has already been unloaded when viewDidUnload gets called. This means that any subviews of the view will no longer be retained by the view. I assume that productImages is a subview of the view controller's view. In that case you have to declare productImages as strong instead of weak if you want it to still be available after the view gets unloaded.

    An other note is that it is very bad practice to start repeating timers in viewDidLoad in invalidating them in viewDidUnload. It is much better to do it in viewDidAppear: and viewWillDisappear:. See this blog post for a detailed explanation http://antonholmquist.com/blog/why-you-really-shouldnt-create-repeating-nstimers-in-init-or-viewdidload/