데이터 전달하기 (동기, 비동기)

https://hellozo0.tistory.com/365

Notification

notificenter : 수정이 일어나면 수정된 내용을 전달하고 노티피케이션 센터를 구독하고 있는 화면에서 수정된 다이어리 객체를 전달받고 뷰에도 수정된 내옹이 갱신되게 구현해볼예정

등록된 이벤트가 발생하면 해당 이벤트들에 대한 행동을 취함. 앱내에서 아무데서나 메시지를 던지면 앱내에서 아무데서나 이 메시지를 받게해주는것 이벤트 버스

post 라는 메서드를 이용해서 이벤트를 전송하고 이벤트를 받으려면 addObserver를 등록하여 포스트한 이벤트를 전달받을수 있다.

Untitled

// 1) Notification을 보내는 ViewController
class PostViewController: UIViewController {
    @IBOutlet var sendNotificationButton: UIButton!
    
    @IBAction func sendNotificationTapped(_ sender: UIButton) {
        guard let backgroundColor = view.backgroundColor else { return }
      
        // Notification에 object와 dictionary 형태의 userInfo를 같이 실어서 보낸다.
        NotificationCenter.default.post(
					name: Notification.Name("notification"), 
					object: sendNotificationButton, 
					userInfo: ["backgroundColor": backgroundColor])
    }
}

// 2) Notification을 받는 ViewController
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 옵저버를 추가해 구독이 가능하게끔 함
        NotificationCenter.default.addObserver(
					self, 
					selector: #selector(notificationReceived(notification:)), 
					name: Notification.Name("notification"), 
					object: nil)
    }
    
    // iOS 9 이상이 아닐 경우에는 removeObserver를 해줘야 함
    deinit {
        NotificationCetner.default.removeObserver(self)
    }
    
    @objc func notificationReceived(notification: Notification) {
        // Notification에 담겨진 object와 userInfo를 얻어 처리 가능
        guard let notificationObject = notification.object as? UIButton else { return }
        print(notificationObject.titleLabel?.text ?? "Text is Empty")
        
        guard let notificationUserInfo = notification.userInfo as? [String: UIColor],
            let postViewBackgroundColor = notificationUserInfo["backgroundColor"] else { return }
        print(postViewBackgroundColor)
    }
}

Delegate(Delegation Design Parttern)