1

Hi I'm here for advice to see whether what I'm doing is the best option is is fine for swift. I have a view controller that I present from viewcontroller1. In viewcontroller2 I have a textfield and when the text is full I save the text to my singleton and initiate an action in view controller 1 through a protocol to save that text to the database and update the uilabels in view controller 1 with those labels and then I dismiss view controller two. I initiate a function from view controller2 in view controller1 to save the data from the singleton to the database. Is this fine to do. If you have any questions feel free to ask.

class ViewController1: UIViewController, EditProtocol{
   var label = UIlabel()
   @IBAction func Editname(_ sender: Any) {
    if let vc = storyboard.instantiateViewController(withIdentifier: "ViewController2Identifier") as? ViewController2{
        vc.controller = self
        vc.modalPresentationStyle = .custom
        vc.modalTransitionStyle = .crossDissolve
        vc.setViewControllers([ProductInformation], animated: true)
        self.present(vc, animated:true, completion: nil)
    }
}

func SaveName() {
    label.text = singleton.shared.text
}

  protocol EditProtocol {
      func SaveName()
   }

 class ViewController2: UIViewController{
       var controller: EditProtocol?
        @IBOutlet weak var Name: UITextField!
        @IBAction func Back(_ sender: AnyObject) {
             singleton.shared.text = Name.text
             controller?. SaveName()
             self.dismiss(animated: true, completion: nil)
           }
     }
rmaddy
  • 314,917
  • 42
  • 532
  • 579
ahmed
  • 115
  • 9

1 Answers1

0

If the only purpose of your singleton is to record this piece of data, then you don't need it. You can directly pass data from VC2 to VC1 and then do saving to database and displaying on UI.

There are several ways to pass data from VC2 back to VC1. Your delegate is fine, you can also use unwind segue, or NotificationCenter (my favorite). All three methods allow you to pass data without need of a singleton object to hold your data. Even more, you can save the data from VC2 directly to database and then read it from VC1. In this way you don't even need one of the three options above to pass data

Fangming
  • 24,551
  • 6
  • 100
  • 90
  • I'm not passing data back, I'm initiating an action once the data is there. The purpose of this question was not about the singleton but was about initiating actions of view controllers from different view controllers. Is what I'm doing above fine. If need be I can reword the question – ahmed Jul 06 '17 at 18:29
  • @ahmed All three options allows you to initiate an action. All three options are good to use. It's okay that you picked the delegate. The only thing I seems wrong in your approach is that singleton so I mentioned that for you. Besides that I cannot see any problem for your design, thats it :) – Fangming Jul 06 '17 at 19:11