Delegates와 Notification 방식의 차이점에 대해 설명하시오.
Delegates와 Notification 방식의 차이 - Neph's iOS blog
앱에서 발생한 이벤트가 현재 화면이 다른 화면까지 영향을 주어야 할 때 외부 라이브러리를 사용하지 않는 다고 할 때 주로 Delegate, Notifiaction를 사용한다.
공통점
모두 이벤트를 다른 화면에 전달할 수 있다는 기능을 가지고 있다.
Delegate
import Foundation
protocol SomeDelegate: AnyObject {
func someFunction(_ view: SomeView, indextPath: Int)
}
import UIKit
final class SomeView: UIView {
weak var delegate: SomeDelegate?
func configureUI() {
delegate?.someFunction(SomeView.Type, indexPath: 1)
}
}
import UIKit
final class SomeViewController: UIViewController {
override viewDidLoad() {
var sampleView = SomeView()
sampleView.delegate = self
self.view.addSubview(sampleView)
}
func updateUI(_ indexPath: Int) {
}
}
extension SomeViewController: SomeDelegate {
func someFunction(_ view: SomeView, indextPath: Int) {
self.updateUI(indexPath)
}
}
Notification
import UIKit
final class PostViewController: UIViewController {
private let sendNotificationButton: UIButton = {
let button = UIButton()
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
sendNotificationButton.addTarget(self, action: #selector(sendNotificationTapped), for: .touchUpInside)
view.addSubview(sendNotificationButton)
NSLayoutConstraint.activate([
sendNotificationButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constraint: -20),
sendNotificationButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constraint: -20),
sendNotificationButton.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constraint: 20)
])
}
@objc 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])
}
}