我创建了一个example project演示通知
处理的同步性质。
通知按预期进行 - 模型初始化期间发布的通知除外。
The Swift Programming Language (Swift 4), Two-Phase Initialization部分解释了初始化的安全检查。在这里,它说:
Safety check 4
An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.
在我的示例中,初始化的第一阶段在调用通知方法之前已完成。并且,如下所示,我还尝试直接调用通知。 View Controller 不会对两者进行操作 - 尽管在初始化之后调用时, View Controller 确实会按预期响应。
这是我应该报告的错误吗?或者我只是在一些关于初始化的简单事情上陷入了脑死亡?
以下是相关模型代码:
class Model {
let notificationONEName = Notification.Name("NotificationONE")
let notificationTWOName = Notification.Name("NotificationTWO")
init() {
notifyObserversTWO()
NotificationCenter.default.post(name: notificationTWOName, object: self)
}
func notifyObserversONE() {
print("START \(Model.self).\(#function)")
NotificationCenter.default.post(name: notificationONEName, object: self)
print("END \(Model.self).\(#function)")
}
}
并且,这是 View Controller 中的观察者端代码:
import UIKit
class ViewController: UIViewController {
let notificationONESelector = #selector(didReceiveNotificationONE)
let notificationTWOSelector = #selector(didReceiveNotificationTWO)
let model = Model()
override func viewDidLoad() {
super.viewDidLoad()
subscribeToNotifications()
model.notifyObserversONE()
model.notifyObserversTWO()
}
func subscribeToNotifications() {
NotificationCenter.default.addObserver(self,
selector: notificationONESelector,
name: model.notificationONEName,
object: model)
NotificationCenter.default.addObserver(self,
selector: notificationTWOSelector,
name: model.notificationTWOName,
object: nil)
}
@objc func didReceiveNotificationONE(notification: Notification) {
print("START \(ViewController.self).\(#function)")
exampleUtilityFunction()
print("END \(ViewController.self).\(#function)")
}
@objc func didReceiveNotificationTWO(notification: Notification) {
print("START \(ViewController.self).\(#function)")
exampleUtilityFunction()
print("END \(ViewController.self).\(#function)")
}
func exampleUtilityFunction() {
print("START \(ViewController.self).\(#function)")
print("END \(ViewController.self).\(#function)")
}
}
最佳答案
在调用 Model.init
时,没有任何东西在观察它。直到调用 Model()
很久之后才调用 subscribeToNotifications
。
如果您想响应此通知,则首先需要在调用 init
之前观察 object: nil
(与第二个通知相同)。这意味着您无法在属性定义中初始化它。您需要调用 subscribeToNotifications
,然后创建 model
。
关于ios - 如果在初始化期间发布通知,则未收到通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47559396/