gpt4 book ai didi

ios - 在 Swift 中使用 NSNotificationCenter 在选项卡栏 Controller 之间传递数据

转载 作者:可可西里 更新时间:2023-11-01 00:53:32 24 4
gpt4 key购买 nike

我第一次尝试在标签栏 Controller 之间传递数据,但它不起作用。第一 Controller :

class FirstViewController: UIViewController {
@IBOutlet weak var sentNotificationLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateNotificationSentLabel:", name: mySpecialNotificationKey, object: nil)
}

@IBAction func notify() {
NSNotificationCenter.defaultCenter().postNotificationName(mySpecialNotificationKey, object: nil, userInfo:["message":"Something"])
}

func updateNotificationSentLabel(notification:NSNotification) {
let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
let messageString = userInfo["message"]
sentNotificationLabel.text = messageString


}
}

在这里它工作正常,sentNotificationLabel.text 是“Something”

Second Controller 类似,但他没有收到任何通知。

class SecondViewController: UIViewController {
@IBOutlet weak var notificationLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLabel:", name: mySpecialNotificationKey, object: nil)
}

func updateLabel(notification:NSNotification) {
let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
let messageString = userInfo["message"]
notificationLabel.text = messageString


}

我做错了什么?如何改变呢?

最佳答案

出现此问题是因为您在注册第二个 View Controller 之前发送消息。

NSNotificationCenter 不支持粘性 通知——换句话说,消息不会被缓存。如果在发送通知的那一刻没有人在听,它就消失了。

最简单的解决方法是在初始化程序中注册您的 SecondViewController 以获取通知。但是,UILabel 尚未加载 - 我们在 viewDidLoad 回调之前。解决方案是在本地缓存接收到的消息,并在准备好时使用它来设置标签文本。

class SecondViewController: UIViewController {

@IBOutlet weak var notificationLabel: UILabel!
var cachedMessage : String? = nil

required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateLabel:", name: mySpecialNotificationKey, object: nil)
}

override func viewDidLoad() {
if let cachedMessage = cachedMessage {
notificationLabel.text = cachedMessage
}
}

func updateLabel(notification:NSNotification) {
let userInfo:Dictionary<String,String!> = notification.userInfo as Dictionary<String,String!>
let messageString = userInfo["message"]
if let notificationLabel = notificationLabel {
notificationLabel.text = messageString
} else {
cachedMessage = messageString
}
}
}

由于 Controller 在显示之前会被初始化,因此应该正确传递消息。

关于ios - 在 Swift 中使用 NSNotificationCenter 在选项卡栏 Controller 之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com