我想在A类到B类中更改变量的值 我已经用下面的代码完成了此操作,但是更改变量的值只能由一个函数完成,如果我在另一个函数(打印测试)中使用它,则返回nil 我在做什么错了??
A类:
ON CONFLICT
B级:
class A: ViewController {
var port : Int? = nil
var server : String? = nil
func updateServerAndport(S:String , p : Int){
server = S
port = p
}
func printTest{
print (server)
}
答案 0 :(得分:0)
只需这样做:
//Update your save function in class B with it.
@IBAction func save(_ sender: Any) {
var dictServerVal:[String: Any] = [:]
dictServerVal["serverText"] = server.text!
dictServerVal["portText"] = port.text!
NotificationCenter.default.post(name: NSNotification.Name.init("YourKeyName"), object: nil, userInfo: dictServerVal)
}
编写A类中的波纹管代码
class A: ViewController {
var port : Int? = nil
var server : String? = nil
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(updateServerAndport(notification:)), name: "YourKeyName", object: nil)
}
func updateServerAndport(notification: NSNotification) {
if let dict = notification.userInfo as? [String: Any] {
if let strServerText = dict["serverText"] as? String, let strPortText = dict["portText"] as? String {
server = strServerText
port = strPortText
}
}
}
答案 1 :(得分:-1)
我要回答自己的问题,只是因为我想将来可能会帮助其他任何人遇到同样的问题。只需要更改以下代码即可:
static var port : Int? = nil
static var server : String? = nil