I have two view controllers, MainVC
and ModalVC
.
When the user taps a button on MainVC
, the modal view controller appears.
The user can then tap another button to dismiss it and return to the main one.
I have tried these two methods and they both accomplish the same thing: they dismiss the modal view controller:
//method 1:
// File: ModalVC.swift
//
@IBAction func dismissTapped() {
self.dismissViewControllerAnimated(false, completion: nil);
}
That works fine as I said, but consider the other method: using delegation to let the main controller do the dismissing:
// method 2: part A
// File: ModalVC.swift
//
protocol ModalVCDelegate {
func modalVCDismissTapped();
}
...
...
...
var delegat:ModalVCDelegate? = nil;
...
...
@IBAction func dismissTapped() {
delegate.modalVCDismissTapped();
}
and on the main view controller custom class file:
// method 2: part B
// File: MainVC.swift
class MainVC : UIViewController, ModalVCDelegate {
...
...
func modalVCDismissTapped() {
self.dismissViewControllerAnimated(false, completion: nil);
}
}
Since these two methods do the needful, should I worry about any possible memory leakage?
Any explanation would help
When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it.
To dismiss the popover after creation, call the dismiss() method on the Popover instance. The popover can also be dismissed from within the popover's view by calling the dismiss() method on the ViewController.
The first option is to tell the view to dismiss itself using its presentation mode environment key. Any view can read its presentation mode using @Environment(\. presentationMode) , and calling wrappedValue. dismiss() on that will cause the view to be dismissed.
Using delegation is the best and more flexible way to dismiss view controller.
The purpose of it is that in some future or in some other place in your code you may reuse this VC, but due of some reasons you may not present it modal, but push into navigation stack. So your ModalVC
does not know how it was presented, but delegate does.
In this case you can have 2 places in your code
You present it modal and delegate calls
[self dismiss...]
You push it into navigation stack and delegate calls
[self.navigationController popView...]
You add it as a child VC and delegate calls
[someParentVC removeChild..]
or any other appropriate workflow to remove it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With