Open Do-hyun-Kim opened 1 year ago
이벤트 발생여부를 옵저버를 등록한 객체들에게 알려주는 방법이다.
NotificationCenter
를 통해 특정한 이름(Notification.Name
)에 해당하는 이벤트를 송신(post
) 한다.NotificationCenter
를 통해 특정한 이름(Notification.Name
에 해당하는 이벤트를 구독하고 수신받는다(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 ObserverViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 옵저버를 추가해 구독이 가능하게끔 함
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived(notification:)), name: Notification.Name("notification"), object: nil)
}
// iOS 9 이상이 아닐 경우에는 removeObserver를 해줘야 함
deinit {
NotificationCenter.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)
}
}
장점
NotificationCenter
같은 외부 객체)가 필요없음단점
장점
Any?
타입의 object
, [AnyHashable: Any]?
타입의 userInfo
로 전달할 수 있음단점
다수의 객체에게 이벤트를 알려야 한다면 Notification을 사용하는 것이 좋을 수 있다. delegate 패턴을 사용하게 되면 로직의 흐름을 따라가기 수월하다는 장점이 있지만, 다수의 객체가 이벤트를 받아야 하기 때문에 그 이벤트를 받는 객체의 수만큼 delegate를 생성하고 뷰들의 depth에 따라 넘겨주고 이벤트 위임 처리를 해야하는 어려움이 있다. Notification을 사용하면 광역적으로(전역적으로) 그러할 필요없이 처리해줄 수 있다.
View
와 ViewController
와 같이 각각의 객체들 사이에서 소통이 필요할 때 사용한다.protocol
을 정의하여 사용함Delegate
로 지정된 객체가 해야 하는 메소드들의 원형을 적어 놓는다Delegate
역할을 하려는 객체는 정의된 protocol
을 따르며 원형만 있던 메소드들의 구현을 한다.delegate
로 지정한 객체에 알려줄 수 있다.NotificationCenter
같은 외부 객체)가 필요 없음.delegate
설정에 nil
이 들어가지 않게 조심해야함. 크래시를 일으킬 수 있음Notification Center
라는 싱글턴 객체를 통해서 이벤트들의 발생 여부를 옵저버를 등록한 객체들에게 Notification
을 post하는 방식으로 사용한다.Notification name
이라는 key 값
을 통해 보내고 받을 수 있다.Notification
과 관련된 정보를 Any?
타입의 object
, [AnyHashable: Any]?
타입의 userInfo
로 전달할 수 있음key 값
으로 Notification의 이름
과 userInfo
를 서로 맞추기 때문에 컴파일 시 구독이 잘 되고 있는지, 올바르게 userInfo
의 value
를 받아오는지 체크가 불가능함Notification post
이후 정보를 받을 수 없음Delegation
을 사용하는 것이 좋다.
Delegate
로 연결을 하면 코드가 읽기도 쉽고 추적이 쉽기때문이다Notification
이 적절할 수 있다.
Delegation
과 Notification
의 가장 큰 차이점은 수신자가 발신자의 정보를 알고 있는지의 여부이다.
Delegation
방식에서는 수신자가 발신자의 정보를 알고 있어야 한다.
하지만 Notification
은 단순히 어떤 값의 변화를 포착하여 그에 맞는 이벤트를 발생시켜주면 된다.
Delegate
를 사용하여 설계하지 않고 Notification
만 가지고 설계를 했다면 다른 사람이 코드를 유지보수할 때 이 Notification
을 누가 Subscribe
하고 있는지 알기가 어렵다.
반면 Delegate
로 설계를 했다면 해당 Delegate의 이름
, 프로토콜의 메서드
등을 통해 어떤 과정에 의해 이벤트 처리 로직이 작동하는지 파악하기 한결 수월하다.
하지만 여러 오브젝트들의 동시에 어떤 이벤트를 받고, 이를 모두 반영해야하는 경우, Notification
이 적절할 수 있다. 이에 대한 예로는 로그인 상태가 변하여 많은 뷰들을 업데이트해야 하는 경우가 있다.
Delegates와 Notification 방식의 차이점에 대해 설명하시오.
NotificationCenter 이란?
NotificationCenter
객체로 부터 어떤 이벤트를 전달 받아 자신에게 등록된 객체들에게 알림을 보내주는 객체이다.Notification
을 발송하면NotificationCenter
에서 메세지를 전달한 observer를 처리할때 까지 대기한다.NotificationCenter
을 통해서 다른 객체간의 데이터를 전달 할 수 있으며, 어플리케이션 어느 곳에도 상호 작용 할 수 있다. 이것은 SingleTone Pattern 의 장점을 사용한 것 같다.Nofication 이란?
NotificationCenter
를 통해 저장하기 위한 구조체 이다.NotificationCenter 예시 코드
NotificationCenter 장점
NotificationCenter
를 통해서 객체들 간의 이벤트 전달을 할 수 있다.NotificationCenter 단점
Notification
Post 이후에 대한 정보를 받을 수 없다.Notification
의 Name과userInfo
를 서로 맞추기 때문에 컴파일 시에 구독이 잘 되고 있는지, 올바르게 userInfo의 Value를 받아오는지 불가능 하다.NotificationCenter
내부적으로 SingleTone Pattern 을 사용하고 있기 때문에 테스트가 어려울 뿐더러, 객체간의 결합도를 높일 수 있다. 때문에 deinit 시에removeObserver
해줘야 한다.Delegates와 Notification 방식의 차이점에 대해 설명하시오.
📝 참고 사이트