London Escorts sunderland escorts 1v1.lol unblocked yohoho 76 https://www.symbaloo.com/mix/yohoho?lang=EN yohoho https://www.symbaloo.com/mix/agariounblockedpvp https://yohoho-io.app/ https://www.symbaloo.com/mix/agariounblockedschool1?lang=EN
4.1 C
New York
Saturday, February 1, 2025

UIKit – loadView vs viewDidLoad


Weak, unowned or sturdy subviews?

I’ve obtained numerous emails and tweets about this matter, so I made a decision to put in writing about it, as a result of it’s actually arduous to discover a correct reply for this query on the web. There are some nice posts and programming guides, some some articles are a bit older, nonetheless many individuals are asking the weak vs sturdy IBOutlet query even on the official boards, however noone actually explains the explanations, even on the boards they solely advocate this WWDC session video. So what is going on on right here? ?

I did some research on the subject and the very very first thing that we must always state is that this: Apple eliminated the viewDidUnload methodology in iOS6 and from that model the iOS view controller lifecycle modified a bit. If you do not know a lot in regards to the lifecycle strategies (demystified), it’s best to learn this text. This was fairly a giant change and Apple additionally touched their inside view administration. Earlier than iOS6 it was a typical apply to outline weak subviews. As a result of they’d a robust reference to it they usually weren’t releasing it except you eliminated it from the view hierarchy.

This was about 10 years in the past. Now why are we nonetheless afraid of sturdy subviews? The primary purpose was the addSubview methodology. The documentation states that it will create a robust reference, which mechanically triggered my mind and I outlined my views as weak pointers, since they are going have a robust reference to their dad and mom. Appears cheap, proper? ?

Weak subviews

Properly, the issue is that if you wish to outline a weak variable we’ve got to make use of an elective, however I do not like the thought of utilizing an elective variable for the reason that view goes to be all the time there, it is a part of the view hierarchy sooner or later in, it is not going anyplace. It is solely going to be “destroyed” when my view controller is deallocated. Ought to I declare it as an implicitly unwrapped elective?!? Perhaps.

import UIKit

class ViewController: UIViewController {

    weak var foo: UILabel! 
    weak var bar: UILabel? 
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()

        
        foo.removeFromSuperview()
        foo.textual content = "crash"
    }
}

Really you possibly can go fallacious with unwrapped weak pointers, as a result of should you take away your view from the view hiearchy sooner or later in time earlier than the view controller deallocation then your weak pointer might be nil. On this case there will not be any extra sturdy references and your view might be deallocated instantly, so if it is an implicitly unwrapped elective, then we’ve got a hassle. Your app will crash should you attempt to entry the property, as a result of it’ll have a 0 worth.

So sure you should use implicitly unwrapped elective variables to retailer subviews, however solely in case you are positive that you’re not going to take away it from the hiearchy. This additionally signifies that you do not belief Apple’s view administration system, which is okay, there may be bugs, however actually that is fairly an important function and it has been round for a decade by now. ?

The opposite various is to make use of a daily weak elective variable, however in that case you may all the time need to verify if it is nil or not, which goes to be a ache within the ass, however at the least you are going to be protected for positive. Private opinion: it will not well worth the effort in any respect and I by no means saved views like this.

Sturdy subviews

My advice is to belief Apple and outline your subviews as sturdy properties. Okay, this will also be problematic when you have different sturdy references to the identical stuff, however typically if the view controller has the one reference to that given subview you have to be completely tremendous.

Since it is a sturdy property you additionally need to initialize the view, however that is not a giant deal. You’ll be able to all the time initialize a view with a .zero body and that is it. Alternatively you possibly can create a subclass with a daily init() methodology, that is even higher, becuase you’re going to use auto format for positive and this fashion can set the translatesAutoresizingMaskIntoConstraints property in a single go.

import UIKit

class Label: UILabel {
    
    init() {
        tremendous.init(body: .zero)

        self.translatesAutoresizingMaskIntoConstraints = false
    }
    
    @accessible(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been applied")
    }
    
    deinit {
        print("deinit Label")
    }
}

class ViewController: UIViewController {

    
    var foo: Label = .init()
    var bar: UILabel = .init(body: .zero)
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        
    }
    
    deinit {
        print("deinit ViewController")
    }
    
}

By implementing a customized deinit methodology and even higher, by making a symbolic breakpoint you possibly can simply detect retain cycles and repair reminiscence points. I made some checks and I can affirm you do not have to be afraid of sturdy views, each the viewcontroller and the view goes to be deallocated if it is wanted. ?

Unowned subviews

Unowned and weak are kind of equal, I might say that you just will not have to outline views as unowned references, as a result of they are often problematic if it involves initialization. It is normally higher to have a weak reference and verify for nil values, however in fact there may be some circumstances the place you may want an unowned subview reference.

Utilizing loadView and viewDidLoad

The loadView methodology can be utilized to create your personal views manually. You need to by no means name this methodology instantly, nevertheless it’s save to override it. The opposite factor that you shouldn’t is that in case you are utilizing this methodology to override the foundation view, then you definitely should not name tremendous.loadView().

import UIKit

class ViewController: UIViewController {
    
    override func loadView() {
        view = UIView(body: .zero)

        
            
    }
}

In each different case once you simply need to add views to the view hierarchy, it is fully tremendous to name the tremendous methodology. I am normally implementing this methodology to setup views and constraints.

import UIKit 

class ViewController: UIViewController {

    var foo: Label = .init()
    
    override func loadView() {
        tremendous.loadView()
        
        view.addSubview(foo)
        
        NSLayoutConstraint.activate([
            view.centerXAnchor.constraint(equalTo: foo.centerXAnchor),
            view.leadingAnchor.constraint(equalTo: foo.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: foo.trailingAnchor),
            foo.heightAnchor.constraint(equalToConstant: 44),
        ])
    }
}

This manner I can make certain that each single view is prepared by the point the viewDidLoad methodology is named. It’s potential to configure views contained in the loadView methodology too, however I favor to maintain the hierarchy setup there and I place all the things else contained in the viewDidLoad operate. I imply controller associated stuff solely, like organising navigation bar buttons and issues like this.

As I discussed this in my earlier article, I favor to make use of subclasses to configure my views, I additionally transfer format constraints there (as a operate that returns them primarily based on some parameters) to maintain the view controller clear. Contained in the viewDidLoad methodology I can carry out further consumer interface associated actions, however that is it I do not use it for including or styling views anymore.

Conclusion

Primarily based on my present information, here’s what I like to recommend for contemporary UIKit builders:

  • Outline your subviews as sturdy properties
  • All the time verify for leaks, implement deinit, use breakpoints or devices
  • Use weak / unowned references if you need to break retain cycles
  • Add views to the hierarchy within the loadView methodology
  • Use subclasses for styling views, make them reusable
  • Outline format constraint getters on the view subclass, activate them inside loadView
  • Carry out remaining UI associated operations within the viewDidLoad operate

That is it. I am not saying that is the proper strategy, however for me it is positively the way in which to go ahead with UIKit. I do know for positive that many individuals are nonetheless working with the framework and it’s right here to remain for a very long time. I hope the following tips will allow you to to grasp UIKit just a bit bit higher. ??

Related Articles

Social Media Auto Publish Powered By : XYZScripts.com