1

Please explain in DETAIL why do we have to write "obj?.mainObj = self" line, in order for the pushViewController method to work?so if i remove the line "obj?.mainObj = self" pushViewController doesn't work,but why?

class ViewController: UIViewController {
    var obj:Bo?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        obj = Bo()
        //  obj?.mainObj = self
        obj?.setupViews()

    }

    func push(){
        print("hello")
        let controller = AppDetailController()
        navigationController?.pushViewController(controller, animated: true)

    }
}

class Bo:UIViewController{

    var mainObj:ViewController?

    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
    }

    func setupViews(){
        mainObj = ViewController()
        mainObj?.push()
    }
}
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
oj229
  • 27
  • 3
  • to hand off one class method to another class you need to call self. To provide a reference from which controller your method(method in another class) is delegated.In short delegation. – Tushar Sharma Nov 04 '17 at 18:25
  • for more understanding read apple doc-: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html. – Tushar Sharma Nov 04 '17 at 18:35
  • if you are trying to push from ViewControler to Bo , you can directly call push function on any button tap or in viewDidAppear.The process you are following here is called delegation. – Tushar Sharma Nov 04 '17 at 18:46
  • And where is AppDetailController ? – Tushar Sharma Nov 04 '17 at 18:51

1 Answers1

0

Your ViewController in BO class is nil. Then "nil"?.push does nothing.

Its nil cause "ViewDidLoad" is not executed when/after u init it. Its executed after its pushed and did load every view in it.

Here: var mainObj:ViewController? U set the init method to init mainObj as nil. Since u put a "?" after the type. Remove it and it will ask for a init that pass the ViewController.

So pass the ViewController on the Init or set it by hand after init it like u are doing.

alegelos
  • 2,308
  • 17
  • 26
  • By definition: open var navigationController: UINavigationController? { get } // If this view controller has been pushed onto a navigation controller, return it. So "self" is a ViewController with a navigationController. And ViewController() have no navigation controller. Again its a "nil"?.pushNav... – alegelos Nov 04 '17 at 18:47
  • @ismail1983 what about selecting my answer as correct? Did it solve ur problem? – alegelos Nov 05 '17 at 22:36