Best way to pass variables from one Swift class to

2019-06-14 18:35发布

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.

3条回答
我想做一个坏孩纸
2楼-- · 2019-06-14 19:03

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
查看更多
ら.Afraid
3楼-- · 2019-06-14 19:13

Don't worry

var firstmyvar = "Any"

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

secondview.myvar = firstmyvar

self.presentViewController(secondview, animated: false, completion: nil)
查看更多
爷的心禁止访问
4楼-- · 2019-06-14 19:16

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.

查看更多
登录 后发表回答