0

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;
soleil
  • 12,133
  • 33
  • 112
  • 183
  • Then this really shouldn't be a concern, anything that iOS decides it needs to release will be released for you. – Mick MacCallum Aug 11 '12 at 21:22
  • But it is a concern because my app crashes... – soleil Aug 11 '12 at 21:27
  • Alright, does it crash when that loop isn't there? – Mick MacCallum Aug 11 '12 at 21:32
  • Your view controller appears to be getting released itself before the loop finishes (or even enters), which means by the time the loop goes to check its condition, your controller is already long gone. – CodaFi Aug 11 '12 at 21:42
  • Do you know why the view controller itself would be getting released? I tried removed that loop, and now I get this: *** -[TheViewController_iPhone isViewLoaded]: message sent to deallocated instance – soleil Aug 11 '12 at 21:49

1 Answers1

0

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/

Anton Holmberg
  • 1,113
  • 12
  • 15