将变量从一个Swift类传递到另一个Swift类的最佳方法?

Ros*_* M. -2 nsuserdefaults ios swift

假设我在一个类中定义变量ViewController,并且想要从另一个类访问该变量,比如说BLEHandler.我该怎么做呢?我遇到了麻烦NSUserDefaults,所以除此之外的方法将不胜感激.

Leo*_*Leo 7

有可能的方法可以在viewControllers之间传递值例如

  • PrepareForSegue
  • NSNotificationCenter
  • 代表
  • 独生子

不同的方式用于不同的情况.

如果使用prepareFoSegue - 在执行segue时想要传递时使用

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

如果你使用notificationcenter - 盲目通知,一个vc发送消息,可能不止一个接收.在发送消息vc

    NSNotificationCenter.defaultCenter().postNotificationName(, object: )
Run Code Online (Sandbox Code Playgroud)

在接收消息vc中首先注册

    NSNotificationCenter.defaultCenter().addObserver(, selector: , name: , object: )
Run Code Online (Sandbox Code Playgroud)

比从选择器获取值

别忘了删除

    NSNotificationCenter.defaultCenter().removeObserver(, name: , object:  )
Run Code Online (Sandbox Code Playgroud)

如果您使用委托 - 接收方和发送方首先建立连接.关于这个可能有帖子,我不会发帖.

如果你使用单身人士 - 你必须清楚单身人士的生命周期.我不建议以这种方式传递价值.