Swift 4: prepare(for segue:) being called after viewDidLoad

12,049

Solution 1

In awakeFromNib you are referencing self.view in order to call layoutIfNeeded. This causes the view to be loaded and viewDidLoad to be called.

If you remove the call to self.view.layoutIfNeeded from awakeFromNib then viewDidLoad will not be called until after prepare(for:sender:). There is no reason to call layoutIfNeeded in awakeFromNib.

Solution 2

viewDidLoad() and awakeFromNib() is called before prepare(for segue: ) because for passing data from one view controller to another you have to initialize and allocate the object So when awakeFromNib is called, it is guaranteed to have all its outlet and action connections already established and than viewDidLoad is called which give assurety the view controller has loaded its view hierarchy into memory. Now its ready for passing data from one viewcontroller to another.

Share:
12,049
Aryan Sharma
Author by

Aryan Sharma

Been writing code since '07. Started from VB now I'm here(Swift). Love to make apps with a superb UX. Love for animations. A firm believer of the fact that 'Looks Matter'. A beautifully designed app will surely sell. Proficiency in iOS Development. Good understanding of Firebase, Google Cloud functions(NodeJS). Handled complete technology wing of a startup for more than 10 months. From backend to frontend, handled everything. Now working as the Lead Engineer at Smartsense.

Updated on June 14, 2022

Comments

  • Aryan Sharma
    Aryan Sharma almost 2 years

    I have 2 VCs: CouponVC and CouponFeedbackVC.

    Coupon VC receives brand: Brand! from its parentViewController. Now I want to pass the brand.name to CouponFeedbackVC.

    CouponVC.swift

    var brandName: String!
    override func viewDidLoad() {
        super.viewDidLoad
        brandName = brand.name
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "couponToFeedBack" {
            if let vc = segue.destination as? CouponFeedbackVC {
                print(brandName)
                vc.brandName = self.brandName
            }
        }
    }
    

    In CouponFeedbackVC.swift

    var brandName: String!
    override func viewDidLoad() {
        super.viewDidLoad()
        print("viewDidLoad")
        print(brandName)
    }
    
     override func awakeFromNib() {
        print(brandName)
        self.view.layoutIfNeeded()
    }
    

    Console Log

    nil
    viewDidLoad
    nil
    StayUncle
    

    awakeFromNib() -> viewDidLoad() -> prepare(for segue:)

    I am not accessing any outlets from CouponFeedbackVC.

    Why is prepare(for segue: ) being called after viewDidLoad() and awakeFromNib()?