20

I'd like to know whether or not both viewDidUnload and dealloc are always called in succession in the UIViewController tear-down process. Is it possible that dealloc could be called on my view controller without viewDidUnload having been called first?

In either case, if I am safely releasing the properties and retained references in both methods it wouldn't be a problem if both methods were called -- but I was wondering if anyone knew for sure or could shed some light on the tear-down process.

2012 Update: It's handy to note that as if iOS 6 viewDidUnload has been deprecated and should be replaced with manual view teardown if required in didReceiveMemoryWarning.

A good article on the new UIView/UIViewContoller and the new behaviour and it's effects on the joe conway blog

Jessedc
  • 12,320
  • 3
  • 50
  • 63

2 Answers2

35

viewDidUnload will not be called every time like dealloc method. viewDidUnload is called only when your app receives low memory warning!

Just think, if you are releasing your object both in viewDidUnload and dealloc methods. If both gets called every time, then you are releasing already released object, which will lead to application crash, isn't it?. viewDidUnload is a place provided by the Apple for cleaning up the things when receiving the low memory warning because you know in iPhone we have memory restriction.

Jessedc
  • 12,320
  • 3
  • 50
  • 63
Manjunath
  • 4,545
  • 2
  • 26
  • 31
  • 1
    I think you mean `viewDidUnload` when you say `viewDidLoad` in your answer. `viewDidLoad` is not called when there's low memory, but when the view is going to appear onscreen (before `viewWillAppear`). `viewDidUnload` is called when there's a low memory warning. – nevan king Jul 10 '10 at 17:26
  • This should have been the correct answer. This got me in trouble today. – asandroq Aug 24 '10 at 20:18
  • It seems like it would be ok to do self.whatever = nil inside of viewDidUnload and then call [_whatever release] inside of dealloc. That way, if viewDidUnload gets called first, then the item will not be overreleased by dealloc because it will be nil'ed out and the release message will just fall away when sent to nil. Can anyone confirm this? – jpswain Nov 30 '11 at 04:57
  • Yes. Once self.whatever has been set to nil, calling [whatever release] becomes a no-op: you're sending the release message to a nil object, not to the whatever object (because it no longer points the object it once held). – SteveCaine Jan 23 '12 at 00:30
0

It is quite thoughtful that, viewDidiUnload method get only called when memory warning appears. Good practise would be to release requisite the object within this method and also make the object nil.