2017-10-31 2 views
0

저는 두 개의 ViewController가 있습니다 : ViewControllerSecondViewController입니다. 이 두 ViewController에 관찰자를 추가했습니다. ViewController에서 알림을 게시 할 IBAction도 정의했습니다. 두 ViewController의 클로저를 통해 알림을 처리합니다. 그러나 ViewController의 폐쇄 만 호출됩니다. SecondViewController에있는 클로저 (심지어 전체 코드까지)가 호출되지 않습니다 (디버거를 사용하여 검사했습니다). 클로저는 print 문만을 포함합니다. 가 여기 내 코드입니다Observer가 NotificationCenter Swift 4.0을 사용하여 호출되지 않습니다.

//ViewController 
import UIKit 

class ViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let nc = NotificationCenter.default 
     nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in 
      print("I'm the : \(type(of: self))") 
     } 
    } 

    @IBAction func sendNotification(_ sender: UIButton) { 
     let nc = NotificationCenter.default 
     nc.post(name: Notification.Name(rawValue:"MyNotification"), object: nil, userInfo: ["message":"Hello there!", "Date:":Date()]) 

    } 
} 

ScondViewController

//SecondViewController 
import UIKit 

class SecondViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     let nc = NotificationCenter.default 
     nc.addObserver(forName: Notification.Name(rawValue:"MyNotification"), object: nil, queue: nil) { (notification) in 
      print("I'm the: \(type(of: self))") 
     } 
    } 
} 

의 ViewController의 폐쇄를 호출하지만 SecondViewController에서 폐쇄하지 않는됩니다. 어쩌면 그 이유는 알림을 게시하기 전에 SecondViewController가 초기화되지 않는다는 것입니다. 그러나 해결책은 어떻게 생겼습니까? 도움을 주시면 감사하겠습니다.

+0

알림을 보내거나 게시 할 때 메모리에 SecondViewController 인스턴스가 있습니까? –

+0

전화가 걸리지 않습니다. 이 통지를 지연과 함께 게시해야합니다. – Mannopson

+0

내가 게시하기 전에 SVC가 초기화되지 않았기 때문에 바로 호출되지 않습니다. 'ViewController'의 viewDidLoad에'let svc = SecondViewController()'를 추가하여 기본 init을 호출했지만 아무 효과가 없습니다. SVC의 클로저가 호출되지 않습니다. 누구나 해결 방법을 알고 있습니까? – user1895268

답변

0

일대일 관계인 경우 위임 패턴을 대신 사용할 수도 있습니다. 비록 당신이 옳긴하지만, 게시물 이전에 초기화하지 않았기 때문에 알림 관찰자는 아직 호출되지 않았습니다. 따라서 SecondViewController에서 함수를 호출해야 할 이유가 없어야합니다.

변수 값을 업데이트하는 데 필요한 경우에만 두 ViewController가 액세스 할 수있는 Variables 클래스의 다른 곳에서이 작업을 수행 할 수 있습니다.

+0

네, 아주 간단한 방법으로 이것을 할 수 있습니다. 하지만 사실 나는 5 ViewController 내가 알리고 싶습니다. 내가 간단하게 유지하고 기본 메커니즘을 이해하기 때문에 나는 단지 두 클래스를 게시했습니다. – user1895268

+0

@ user1895268 나머지 viewController에서 검색하기가 어렵습니다. 즉시 게시 된 알림 – Mannopson

+0

아주 간단한 방법으로 해결 방법을 찾았습니다. 옵저버를 추가하는 코드는 viewDidLoad에 있으면 안됩니다. 대신 나는'SecondViewController'에서 클래스 func'class func setObserver()'를 만들었습니다. 내'ViewController'에서'viewDidLoad'에서 나는 단지'SecondViewController.setObserver()'를 추가했고 그것은 트릭을합니다. 의견을 보내 주셔서 감사합니다. – user1895268

관련 문제