Best way to pass variables from one Swift class to another?

你。 提交于 2019-12-08 15:29:12

问题


Suppose I define variable in one class, ViewController, and want to access that variable from another class, say BLEHandler. How do I go about doing that? I've had trouble with NSUserDefaults, so a method besides that would be greatly appreciated.


回答1:


There are may ways you can pass value between viewControllers For example

  • PrepareForSegue
  • NSNotificationCenter
  • Delegate
  • Singleton

Different way is used in different case.

If you use prepareFoSegue- is used when you want to pass when perform segue

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        //Use below to get reference,so that you can pass value
        //segue.destinationViewController 
        //segue.sourceViewController
}

If you use notificationcenter - blind notification,one vc send message,may more than one to receive. In send message vc

    NSNotificationCenter.defaultCenter().postNotificationName(, object: )

In receive message vc Register first

    NSNotificationCenter.defaultCenter().addObserver(, selector: , name: , object: )

Than you get the value from the selector

Do not forget to remove

    NSNotificationCenter.defaultCenter().removeObserver(, name: , object:  )

If you use delegate - the receiver and sender has a connection first. There are may post about this,I will not post example.

If you use singleton - you have to be clear about the life circle of singleton. I do not suggest to pass value in this way.




回答2:


Don't worry

var firstmyvar = "Any"

let secondview = self.storyboard?.instantiateViewControllerWithIdentifier("secondview") as SecondViewController

secondview.myvar = firstmyvar

self.presentViewController(secondview, animated: false, completion: nil)



回答3:


One way is to create a variable in app delegate. Its global to your view controllers.

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable


来源:https://stackoverflow.com/questions/29737959/best-way-to-pass-variables-from-one-swift-class-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!