【发布时间】:2021-03-05 09:08:45
【问题描述】:
我正在尝试学习如何将 NSNotification 用于我正在从事的项目,由于我以前从未使用过它,所以我首先尝试学习如何使用它;每次我尝试遵循 youtube 教程或在线找到的教程时,我的代码似乎都不起作用。此外,在尝试调试问题时,它显示代码的观察者部分没有进入 @obj c 函数。下面是我的代码,展示了它是如何用于发布和观察通知的。
extension Notification.Name {
static let notifyId = Notification.Name("NotifyTest")
}
ViewController.swift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
var test: ObserverObj = ObserverObj(observerLblText: "Observing")
@IBAction func notifyObserver(_ sender: Any) {
let vc = storyboard?.instantiateViewController(identifier: "ObserverVC")
vc?.modalPresentationStyle = .fullScreen
guard let vcL = vc else {
return
}
NotificationCenter.default.post(name: .notifyId, object: nil)
self.navigationController?.pushViewController(vcL, animated: true)
}
}
NotificationTestViewController.swift
import UIKit
class NotificationTestViewController: UIViewController {
@IBOutlet weak var observerLbl: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(observingFunc(notification:)), name: .notifyId, object: nil)
// Do any additional setup after loading the view.
}
@objc func observingFunc(notification: Notification) {
observerLbl.text = "notifying"//text.test.observerLblText
}
有人可以帮助我,让我知道我哪里出了问题,因为我已经尝试了 2 天。
【问题讨论】:
-
首先,您的示例非常不实用,因为您可以直接传递数据。最可能的原因是通知是在添加观察者之前发布的。添加打印行以找出答案。通知仅在发送者和接收者不直接相关或有多个接收者时才有用。
-
我知道通知有用的原因,这就是我需要它们的原因。另外,我只是想在申请之前先练习如何使用它。我一直在添加打印行以查看哪里出错了,但我仍然看不到导致此问题的原因。
标签: ios swift swift5 nsnotificationcenter