Why does bad practice have a viewController?

I have two view controllers, MainVC and ModalVC .

When the user presses a button on MainVC , a modal view manager appears.

The user can click another button to cancel it and return to the main one.

I tried these two methods, and they both do the same thing: they reject the modal view controller:

 //method 1: // File: ModalVC.swift // @IBAction func dismissTapped() { self.dismissViewControllerAnimated(false, completion: nil); } 

This works fine, as I said, but consider another method: using delegation allows the main controller to reject:

 // method 2: part A // File: ModalVC.swift // protocol ModalVCDelegate { func modalVCDismissTapped(); } ... ... ... var delegat:ModalVCDelegate? = nil; ... ... @IBAction func dismissTapped() { delegate.modalVCDismissTapped(); } 

and in the user class file of the main control controller:

 // method 2: part B // File: MainVC.swift class MainVC : UIViewController, ModalVCDelegate { ... ... func modalVCDismissTapped() { self.dismissViewControllerAnimated(false, completion: nil); } } 

Since these two methods make it necessary, should I worry about any possible memory leak?

Any explanation will help

+8
ios uiviewcontroller swift
source share
1 answer

Using delegation is a better and more flexible way to reject a view controller.
The purpose of this is that in some future or elsewhere in your code, you can reuse this VC, but for some reason you cannot present it modally, but click on the navigation stack. Thus, your ModalVC does not know how it was presented, but delegates.
In this case, you can have 2 places in your code

  • You present it modal and delegate calls

     [self dismiss...] 
  • You push it into the navigation stack and delegate the call

     [self.navigationController popView...] 
  • You add it as a child of VC and delegate calls

     [someParentVC removeChild..] 

    or any other appropriate workflow to delete it.

+13
source share

All Articles