★ TouchArcade needs your help. Click here to support us on Patreon.

UIView cleanup best practices?

04-30-2009, 01:53 PM
#1
Joined: Jan 2009
Posts: 101
UIView cleanup best practices?

Let's say I've added a UIView and then added multiple subviews to that view. From a cleanup perspective, do I need to bother calling removeFromSuperview on the subviews, or is just removing the parent view good enough?

I realize that I'd need to release any alloc'ed subviews to free up memory, just not sure if there's any other cleanup I'd need to do if I removed the views from the scene.

thanks!
04-30-2009, 04:14 PM
#2
Joined: Mar 2009
Location: BC, Canada
Posts: 10
When a view reference count gets to 0, it's dealloc method is called which does one release for each subview (the reference count of each subview decreases by one). If no other object holds a reference to the subviews, then their reference count will become 0 and their dealloc method will be called.

Calling removeFromSuperview decrements the reference count by one because the parent releases it reference to it. If no other object holds a reference to the subview, then its reference count will become 0 and its dealloc method will be called.

The net effect is the same:

Operation Ref Ref
Delta Count
------------------------------
a = [UIView alloc] ++a a=1
b = [UIView alloc] ++b b=1
[b addSubview:a] ++a a=2
[a release] --a a=1
:
:
[b release] --b b=0 -> [b dealloc] --a a=0 -> [a dealloc]

Operation Ref Ref
Delta Count
------------------------------
a = [UIView alloc] ++a a=1
b = [UIView alloc] ++b b=1
[b addSubview:a] ++a a=2
[a release] --a a=1
:
:
[a removeFromSuperview] --a a=0 -> [a dealloc]
[b release] --b b=0 -> [b dealloc]

Wopiti - Social gaming, on the move.

Wopiti Words - Addictive word finding game featuring exciting multiplayer action

Last edited by luis; 04-30-2009 at 04:17 PM.
04-30-2009, 04:15 PM
#3
You need to call removeFromSuperview for each subview. Just removing parent isn't enough. When you remove subview from superview it is also released automatically.

If you want to be notified about new games, visit iPlayful page on facebook and become a fan.
If you are interested in game development, follow me on twitter.