将变量从一个 Swift class 传递到另一个的最佳方法?
Best way to pass variables from one Swift class to another?
假设我在一个 class、ViewController
中定义了变量,并想从另一个 class(比如 BLEHandler
)访问该变量。我该怎么做呢?我在使用 NSUserDefaults
时遇到了麻烦,因此非常感谢除此之外的方法。
一种方法是在应用委托中创建一个变量。它对您的视图控制器是全局的。
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable
别担心
var firstmyvar = "Any"
let secondview = self.storyboard?.instantiateViewControllerWithIdentifier("secondview") as SecondViewController
secondview.myvar = firstmyvar
self.presentViewController(secondview, animated: false, completion: nil)
您可以通过多种方式在 viewController 之间传递值
例如
- PrepareForSegue
- NSNotificationCenter
- 代表
- 单例
不同情况使用不同方式
If you use prepareFoSegue- 执行segue时想通过时使用
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//Use below to get reference,so that you can pass value
//segue.destinationViewController
//segue.sourceViewController
}
如果你使用notificationcenter - 盲通知,一个vc发送消息,可能会有多个接收。
在发送消息vc
NSNotificationCenter.defaultCenter().postNotificationName(, object: )
正在接收消息vc
先注册
NSNotificationCenter.defaultCenter().addObserver(, selector: , name: , object: )
比你从选择器中得到值
别忘了删除
NSNotificationCenter.defaultCenter().removeObserver(, name: , object: )
如果使用委托 - 接收方和发送方首先建立连接。
关于这个可能有post,我就不post举例了。
如果你用单例——你要清楚单例的生活圈。我不建议这样传值。
假设我在一个 class、ViewController
中定义了变量,并想从另一个 class(比如 BLEHandler
)访问该变量。我该怎么做呢?我在使用 NSUserDefaults
时遇到了麻烦,因此非常感谢除此之外的方法。
一种方法是在应用委托中创建一个变量。它对您的视图控制器是全局的。
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable
别担心
var firstmyvar = "Any"
let secondview = self.storyboard?.instantiateViewControllerWithIdentifier("secondview") as SecondViewController
secondview.myvar = firstmyvar
self.presentViewController(secondview, animated: false, completion: nil)
您可以通过多种方式在 viewController 之间传递值 例如
- PrepareForSegue
- NSNotificationCenter
- 代表
- 单例
不同情况使用不同方式
If you use prepareFoSegue- 执行segue时想通过时使用
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//Use below to get reference,so that you can pass value
//segue.destinationViewController
//segue.sourceViewController
}
如果你使用notificationcenter - 盲通知,一个vc发送消息,可能会有多个接收。 在发送消息vc
NSNotificationCenter.defaultCenter().postNotificationName(, object: )
正在接收消息vc 先注册
NSNotificationCenter.defaultCenter().addObserver(, selector: , name: , object: )
比你从选择器中得到值
别忘了删除
NSNotificationCenter.defaultCenter().removeObserver(, name: , object: )
如果使用委托 - 接收方和发送方首先建立连接。 关于这个可能有post,我就不post举例了。
如果你用单例——你要清楚单例的生活圈。我不建议这样传值。