将变量从一个 Swift 类传递到另一个的最佳方法? [英] Best way to pass variables from one Swift class to another?
问题描述
假设我在一个类中定义了变量,ViewController
,并且想要从另一个类访问该变量,比如 BLEHandler
.我该怎么做?我在使用 NSUserDefaults
时遇到了麻烦,所以除此之外的方法将不胜感激.
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.
推荐答案
可以通过多种方式在 viewController 之间传递值例如
There are may ways you can pass value between viewControllers For example
- 为Segue做准备
- NSNotificationCenter
- 委托
- 单身
不同的情况使用不同的方式.
Different way is used in different case.
如果你使用prepareFoSegue-当你想在执行segue时传递
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
}
如果您使用通知中心 - 盲通知,一个vc发送消息,可能不止一个接收.在发送消息 vc
If you use notificationcenter - blind notification,one vc send message,may more than one to receive. In send message vc
NSNotificationCenter.defaultCenter().postNotificationName(, object: )
在接收消息vc中先注册
In receive message vc Register first
NSNotificationCenter.defaultCenter().addObserver(, selector: , name: , object: )
比你从选择器中得到的值
Than you get the value from the selector
不要忘记删除
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.
这篇关于将变量从一个 Swift 类传递到另一个的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!