I have a view which can have several different states (display a waiting animation, a count down, a recording screen...), each state corresponding to one of this view's direct subviews:
My idea then is to have a status variable, and add a property observer to show only the related view:
enum Status {
case waiting
case countDown
// ...
}
var status: Status = .loading { didSet { showRelevantView() } }
func showRelevantView() {
waitingView.isHidden = status != .waiting
countDownView.isHidden = status != .countDown
// ...
}
Given this, only one of the six subviews would be shown. I would like to know, however, if the five other subviews may put pressure on the memory, and if so, what would be a good solution to improve this?
Thank you for your help
CodePudding user response:
Yes, hidden views use memory. How much? Well, it depends of course on the complexity of the views.
Try this simple example:
class HiddenViewsTestViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add a tap gesture recognizer
let t = UITapGestureRecognizer(target: self, action: #selector(tapped(_:)))
view.addGestureRecognizer(t)
}
@objc func tapped(_ g: UITapGestureRecognizer) -> Void {
// add 500 hidden views
for _ in 1...500 {
let v = UIView()
v.backgroundColor = .cyan
v.frame = CGRect(x: 0, y: 0, width: 200, height: 300)
view.addSubview(v)
v.isHidden = true
}
}
}
When you launch it, select the Debug Navigator
in the Navigator pane (in Xcode). Note the memory value. With each tap in the view, the code will add 500 hidden views. Note the corresponding increases in memory used.
To determine the effect your app with your views, you should Profile
your app and use Instruments to get a clear measure of the memory being used.
If it's a relatively small amount, you probably have nothing to worry about... but, as we have no idea what your hidden views are, or what else you're doing in this situation, you can only make the decision after you've done the testing / profiling.