Passing data from model to controller












2















I am wondering what would be the best practice when I want to pass data from model to controller.



What I want to do

I would like to update a label when the time changes.



CurrentTime.swift (Model)



var timer: Timer?
var currentTime: String?

init() {
if timer == nil{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
}
}

@objc private func updateCurrentTime(){
let df = DateFormatter()
df.dateFormat = "HH:mm"
df.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
}


ViewController.swift



class ViewController: UIViewController {

@IBOutlet var timeLabel: UILabel!
var currentTime = CurrentTime()

override func viewDidLoad() {
}

@IBAction func closeBtnWasPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}









share|improve this question























  • You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

    – Paulw11
    Nov 24 '18 at 12:59
















2















I am wondering what would be the best practice when I want to pass data from model to controller.



What I want to do

I would like to update a label when the time changes.



CurrentTime.swift (Model)



var timer: Timer?
var currentTime: String?

init() {
if timer == nil{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
}
}

@objc private func updateCurrentTime(){
let df = DateFormatter()
df.dateFormat = "HH:mm"
df.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
}


ViewController.swift



class ViewController: UIViewController {

@IBOutlet var timeLabel: UILabel!
var currentTime = CurrentTime()

override func viewDidLoad() {
}

@IBAction func closeBtnWasPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}









share|improve this question























  • You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

    – Paulw11
    Nov 24 '18 at 12:59














2












2








2








I am wondering what would be the best practice when I want to pass data from model to controller.



What I want to do

I would like to update a label when the time changes.



CurrentTime.swift (Model)



var timer: Timer?
var currentTime: String?

init() {
if timer == nil{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
}
}

@objc private func updateCurrentTime(){
let df = DateFormatter()
df.dateFormat = "HH:mm"
df.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
}


ViewController.swift



class ViewController: UIViewController {

@IBOutlet var timeLabel: UILabel!
var currentTime = CurrentTime()

override func viewDidLoad() {
}

@IBAction func closeBtnWasPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}









share|improve this question














I am wondering what would be the best practice when I want to pass data from model to controller.



What I want to do

I would like to update a label when the time changes.



CurrentTime.swift (Model)



var timer: Timer?
var currentTime: String?

init() {
if timer == nil{
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCurrentTime), userInfo: nil, repeats: true)
}
}

@objc private func updateCurrentTime(){
let df = DateFormatter()
df.dateFormat = "HH:mm"
df.timeZone = TimeZone.current
let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
}


ViewController.swift



class ViewController: UIViewController {

@IBOutlet var timeLabel: UILabel!
var currentTime = CurrentTime()

override func viewDidLoad() {
}

@IBAction func closeBtnWasPressed(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}






ios swift model-view-controller






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 12:43









Tech IRISTech IRIS

237




237













  • You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

    – Paulw11
    Nov 24 '18 at 12:59



















  • You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

    – Paulw11
    Nov 24 '18 at 12:59

















You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

– Paulw11
Nov 24 '18 at 12:59





You can post a Notification or provide a way to register observer closures with your model. You should set up the date formatter as a lazy private property rather than creating it each time the timer fires. Dateformatters are relatively expensive to create.

– Paulw11
Nov 24 '18 at 12:59












2 Answers
2






active

oldest

votes


















1














Option 1



1- Add this var



weak var delegate: ViewController?


2- in viewDidLoad of the vc



currentTime.delegate = self


3-



let timezoneDate = df.string(from: Date())
currentTime = timezoneDate
delegate?.update(currentTime)


4- inside the vc



func update(_ data:String) {
lbl.text = data
}


off course you can do



delegate?.lbl.text = currentTime


but above is MVC



Option 2



var ob:NSKeyValueObservation!


and in viewDidLoad



ob =  currentTime.observe(CurrentTime.currentTime, options: .new) { cur, tex in
timeLabel.text = tex
}





share|improve this answer

































    1














    You should define a Dynamic class like this:



    class Dynamic<T> {

    var bind: (T) -> Void = { _ in }

    var value: T? {
    didSet {
    bind(value!)
    }
    }

    init(_ v: T) {
    value = v
    }
    }


    In your model change definition of the currentTime property like this:



    var currentTime: Dynamic<String>


    In your controller in viewDidLoad method add these codes:



    yourModel.currentTime.bind = { [weak self] time in
    self?.timeLabel.text = time
    }





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458265%2fpassing-data-from-model-to-controller%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Option 1



      1- Add this var



      weak var delegate: ViewController?


      2- in viewDidLoad of the vc



      currentTime.delegate = self


      3-



      let timezoneDate = df.string(from: Date())
      currentTime = timezoneDate
      delegate?.update(currentTime)


      4- inside the vc



      func update(_ data:String) {
      lbl.text = data
      }


      off course you can do



      delegate?.lbl.text = currentTime


      but above is MVC



      Option 2



      var ob:NSKeyValueObservation!


      and in viewDidLoad



      ob =  currentTime.observe(CurrentTime.currentTime, options: .new) { cur, tex in
      timeLabel.text = tex
      }





      share|improve this answer






























        1














        Option 1



        1- Add this var



        weak var delegate: ViewController?


        2- in viewDidLoad of the vc



        currentTime.delegate = self


        3-



        let timezoneDate = df.string(from: Date())
        currentTime = timezoneDate
        delegate?.update(currentTime)


        4- inside the vc



        func update(_ data:String) {
        lbl.text = data
        }


        off course you can do



        delegate?.lbl.text = currentTime


        but above is MVC



        Option 2



        var ob:NSKeyValueObservation!


        and in viewDidLoad



        ob =  currentTime.observe(CurrentTime.currentTime, options: .new) { cur, tex in
        timeLabel.text = tex
        }





        share|improve this answer




























          1












          1








          1







          Option 1



          1- Add this var



          weak var delegate: ViewController?


          2- in viewDidLoad of the vc



          currentTime.delegate = self


          3-



          let timezoneDate = df.string(from: Date())
          currentTime = timezoneDate
          delegate?.update(currentTime)


          4- inside the vc



          func update(_ data:String) {
          lbl.text = data
          }


          off course you can do



          delegate?.lbl.text = currentTime


          but above is MVC



          Option 2



          var ob:NSKeyValueObservation!


          and in viewDidLoad



          ob =  currentTime.observe(CurrentTime.currentTime, options: .new) { cur, tex in
          timeLabel.text = tex
          }





          share|improve this answer















          Option 1



          1- Add this var



          weak var delegate: ViewController?


          2- in viewDidLoad of the vc



          currentTime.delegate = self


          3-



          let timezoneDate = df.string(from: Date())
          currentTime = timezoneDate
          delegate?.update(currentTime)


          4- inside the vc



          func update(_ data:String) {
          lbl.text = data
          }


          off course you can do



          delegate?.lbl.text = currentTime


          but above is MVC



          Option 2



          var ob:NSKeyValueObservation!


          and in viewDidLoad



          ob =  currentTime.observe(CurrentTime.currentTime, options: .new) { cur, tex in
          timeLabel.text = tex
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 24 '18 at 13:06

























          answered Nov 24 '18 at 12:57









          Sh_KhanSh_Khan

          40.8k51125




          40.8k51125

























              1














              You should define a Dynamic class like this:



              class Dynamic<T> {

              var bind: (T) -> Void = { _ in }

              var value: T? {
              didSet {
              bind(value!)
              }
              }

              init(_ v: T) {
              value = v
              }
              }


              In your model change definition of the currentTime property like this:



              var currentTime: Dynamic<String>


              In your controller in viewDidLoad method add these codes:



              yourModel.currentTime.bind = { [weak self] time in
              self?.timeLabel.text = time
              }





              share|improve this answer




























                1














                You should define a Dynamic class like this:



                class Dynamic<T> {

                var bind: (T) -> Void = { _ in }

                var value: T? {
                didSet {
                bind(value!)
                }
                }

                init(_ v: T) {
                value = v
                }
                }


                In your model change definition of the currentTime property like this:



                var currentTime: Dynamic<String>


                In your controller in viewDidLoad method add these codes:



                yourModel.currentTime.bind = { [weak self] time in
                self?.timeLabel.text = time
                }





                share|improve this answer


























                  1












                  1








                  1







                  You should define a Dynamic class like this:



                  class Dynamic<T> {

                  var bind: (T) -> Void = { _ in }

                  var value: T? {
                  didSet {
                  bind(value!)
                  }
                  }

                  init(_ v: T) {
                  value = v
                  }
                  }


                  In your model change definition of the currentTime property like this:



                  var currentTime: Dynamic<String>


                  In your controller in viewDidLoad method add these codes:



                  yourModel.currentTime.bind = { [weak self] time in
                  self?.timeLabel.text = time
                  }





                  share|improve this answer













                  You should define a Dynamic class like this:



                  class Dynamic<T> {

                  var bind: (T) -> Void = { _ in }

                  var value: T? {
                  didSet {
                  bind(value!)
                  }
                  }

                  init(_ v: T) {
                  value = v
                  }
                  }


                  In your model change definition of the currentTime property like this:



                  var currentTime: Dynamic<String>


                  In your controller in viewDidLoad method add these codes:



                  yourModel.currentTime.bind = { [weak self] time in
                  self?.timeLabel.text = time
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 24 '18 at 13:01









                  Hasti RanjkeshHasti Ranjkesh

                  219112




                  219112






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53458265%2fpassing-data-from-model-to-controller%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Contact image not getting when fetch all contact list from iPhone by CNContact

                      count number of partitions of a set with n elements into k subsets

                      A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks