我有2个类,我尝试使用NotificationsCenter和Observers发送布尔值。
如果布尔值发送正确,那么我想在ViewController上导航。
但是很不幸,由于某些原因,我从Observer(checkIsUserFromChecklist
)开始的功能未触发。
这是我的代码:
extension Notification.Name {
static let isAccessedFromChecklistVC = Notification.Name(rawValue: "isAccessedFromChecklistVC")
}
// Class where I want to check if the boolean is changed
class ChecklistVC: UIViewController {
var isAccessedFromChecklist = true
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.post(name: .isAccessedFromChecklistVC, object: isAccessedFromChecklist)
}
//…
//…
//…
}
// Class where I want to get the value of the boolean
class FullscreenImageVC: UIViewController {
var isAccessedFromChecklistVC = false
// Remove observer from memory after we use it
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
createObservers()
}
func createObservers(){
NotificationCenter.default.addObserver(self,
selector: #selector(checkIfIsAccessedFromChecklist),
name: .isAccessedFromChecklistVC,
object: nil)
}
@objc func checkIfIsAccessedFromChecklist(_ notification: Notification){
if let object = notification.object as? Bool{
print("Object status: \(object)") // Is never entering here.
isAccessedFromChecklistVC = object
}
}
func navigateToChecklist(){
if isAccessedFromChecklistVC == true {
let checklistVC = self.storyboard?.instantiateViewController(withIdentifier: "ChecklistVC") as! ChecklistVC
self.navigationController?.setViewControllers([self.navigationController!.viewControllers.first!, checklistVC], animated: true)
}
}
}
感谢您阅读。
答案 0 :(得分:1)
该帖子似乎是
NotificationCenter.default.post(name: .isAccessedFromChecklistVC, object: isAccessedFromChecklist)
在FullscreenImageVC
vc注册为观察者之前
NotificationCenter.default.addObserver(self,
selector: #selector(checkIfIsAccessedFromChecklist),
name: .isAccessedFromChecklistVC
object: nil)
因此,请确保在第二个vc处于活动状态时进行发布