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