【发布时间】:2017-11-29 18:26:36
【问题描述】:
我创建了一个example project 来演示Notification 处理的同步性质。
通知按预期处理 - 模型初始化期间发布的通知除外。
The Swift Programming Language (Swift 4), Two-Phase Initialization 部分解释了初始化的安全检查。在这里,它说:
安全检查 4
初始化程序不能调用任何实例方法,请阅读 任何实例属性的值,或将 self 称为值 直到初始化的第一阶段完成。
在我的示例中,在调用通知方法之前,初始化的第一阶段已完成。而且,如下图,我也试过直接调用通知。视图控制器都不会执行任何操作 - 尽管在初始化后调用 时,视图控制器确实会按预期响应。
这是我应该报告的错误吗?还是我只是在初始化一些简单的事情上脑残?
以下是相关型号代码:
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)")
}
}
还有,这是视图控制器中的观察者端代码:
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)")
}
}
【问题讨论】:
标签: ios swift notifications ios11 swift4