https://hellozo0.tistory.com/365

Notification

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

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

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

// 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)

하나의 객체가 다른 객체를 대신해 동작 또는 조정할 수 있는 기능을 제공합니다.

델리게이션 디자인 패턴은 Foundation, UIKit, AppKit 그리고 Cocoa Touch 등 애플의 프레임워크에서 광범위하게 활용하고 있습니다.

주로 프레임워크 객체가 위임을 요청하며, (주로 애플리케이션 프로그래머가 작성하는) 커스텀 컨트로러 객체가 위임을 받아 특정 이벤트에 대한 기능을 구현합니다.

델리게이션 디자인 패턴은 커스텀 컨트롤러에서 세부동작을 구현함으로써 동일한 동작에 대해 다양한 대응을 할 수 있게 해줍니다.

ex) UITextFieldDelegate

Untitled

protocol을 정의하여 사용한다.

// 1) Delegate 프로토콜 선언
protocol SomeDelegate {
    func someFunction(someProperty: Int)
}

class SomeView: UIView {
    // 2) 순환 참조를 막기 위해 weak으로 delegate 프로퍼티를 가지고 있음
    weak var delegate: SomeDelegate?
    
    func someTapped(num: Int) {
        // 3) 이벤트가 일어날 시 delegate가 동작하게끔 함
        delegate?.someFunction(someProperty: num)
    }
}
// 4) Delegate 프로토콜을 따르도록 함
class SomeController: SomeDelegate {
    var view: SomeView?
    
    init() {
        view = SomeView()
        // 6) delegate를 자신으로 설정
        view?.delegate = self
        someFunction(someProperty: 0)
    }
    
    // 5) Delegate 프로토콜에 적힌 메소드 구현
    func someFunction(someProperty: Int) {
        print(someProperty)
    }
}

let someController = SomeController()
// prints 0

Protocols - The Swift Programming Language (Swift 5.7)