Notification
처리의 동기 성을 보여주기 위해 example project을 만들었습니다.초기화 중에 게시되면 알림을받지 못했습니까?
알림은 예상대로 처리됩니다. 모델 초기화 중에 게시되는 경우는 예외입니다.
The Swift Programming Language (Swift 4), Two-Phase Initialization 섹션에서는 초기화에 대한 안전성 검사에 대해 설명합니다. 여기서, 말한다
안전 점검 4 인스턴스 메소드를 호출 할 수없는 이니셜 모든 인스턴스 성질 값을 읽거나 초기화의 첫 단계 후까지의 값 으로 자기 참조
완료되었습니다.
알림 메서드가 호출되기 전에 은이 예제에서 완료되었습니다. 아래에 나와있는 것처럼 알림을 직접 호출하려고했습니다. 어느 쪽도보기 컨트롤러에 의해 작동하지 않습니다 - 초기화 후 호출 될 때,보기 컨트롤러가 예상대로 응답하지 않습니다.
신고해야하는 버그입니까? 아니면 초기화와 관련하여 간단한 일에 뇌사 상태가되는 순간입니까?
가 여기에 해당 모델 코드입니다 :
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)")
}
}
그리고, 여기에 뷰 컨트롤러의 관찰자 측 코드입니다 : Model.init
가 호출되는 시점에서
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)")
}
}
그리고 모델에서 알림 이름 상수를 검색 할 수도 없습니다. 이봐. 확실히 뇌사 상태입니다! 고마워, 롭. – leanne