Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()?

like image 612
Aryan Sharma Avatar asked Oct 07 '17 07:10

Aryan Sharma


2 Answers

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.

like image 88
Paulw11 Avatar answered Nov 19 '22 04:11

Paulw11


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.

like image 24
Nitesh Kumar Garg Avatar answered Nov 19 '22 04:11

Nitesh Kumar Garg