-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Delegates와 Notification 방식의 차이점에 대해 설명하시오. #14
Comments
Delegates와 Notification 방식의 차이점에 대해 설명하시오.NotificationCenter 이란?
Nofication 이란?
public struct Notification : ReferenceConvertible, Equatable, Hashable {
/// A tag identifying the notification.
public var name: Notification.Name
/// An object that the poster wishes to send to observers.
///
/// Typically this is the object that posted the notification.
public var object: Any?
/// Storage for values or objects related to this notification.
public var userInfo: [AnyHashable : Any]?
} NotificationCenter 예시 코드extension Notification.Name {
static let didDeliveName = Notification.Name("didDeliveName")
static let didDeliveAge = Notification.Name("didDeliveAge")
}
class Jenny {
func didDeliveName() {
NotificationCenter.default.post(name: NSNotification.Name.didDeliveName, object: "jenny")
}
func didDeliveAge() {
NotificationCenter.default.post(name: NSNotification.Name.didDeliveAge, object: 26)
}
}
class Company {
var employeeName: String?
var employeeAge: Int?
init() {
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveName(_:)), name: .didDeliveName, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveAge(_:)), name: .didDeliveAge, object: nil)
}
@objc
private func didReceiveName(_ notification: Notification) {
/// 해당 notification 에서는 jenny object 만 넘겨짐 -> didReceiveName 식별자에게 전달되는 데이터는 "jenny" 이기 떄문
print("object Data: \(notification.object)")
guard let employeeName = notification.object as? String else { return }
self.employeeName = employeeName
}
@objc
private func didReceiveAge(_ notification: Notification) {
/// 해당 notification 에서는 26 object 만 넘겨짐 -> didReceiveAge 식별자에게 전달되는 데이터는 26 이기 떄문
print("object age data: \(notification.object)")
guard let employeeAge = notification.object as? Int else { return }
self.employeeAge = employeeAge
}
}
let jenny: Jenny = Jenny()
let myCompany: Company = Company()
jenny.didDeliveName()
jenny.didDeliveAge()
print(myCompany.employeeName)
print(myCompany.employeeAge) NotificationCenter 장점
NotificationCenter 단점
Delegates와 Notification 방식의 차이점에 대해 설명하시오.
📝 참고 사이트 |
Notification 이란이벤트 발생여부를 옵저버를 등록한 객체들에게 알려주는 방법이다.
// 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)
}
} Delegate와 Notification의 차이점delegate
Notification
무엇을 사용하는 것이 좋을까다수의 객체에게 이벤트를 알려야 한다면 Notification을 사용하는 것이 좋을 수 있다. delegate 패턴을 사용하게 되면 로직의 흐름을 따라가기 수월하다는 장점이 있지만, 다수의 객체가 이벤트를 받아야 하기 때문에 그 이벤트를 받는 객체의 수만큼 delegate를 생성하고 뷰들의 depth에 따라 넘겨주고 이벤트 위임 처리를 해야하는 어려움이 있다. Notification을 사용하면 광역적으로(전역적으로) 그러할 필요없이 처리해줄 수 있다. 📝 참고 사이트 |
Delegate
Delegate 사용 장점
Delegate 단점
Notification
Notification 사용 장점
Notification 사용 단점
📝 참조 |
공통점
Delegation특징
장점
단점
Notification특징
장점
단점
어디에 써야할까?
정리
하지만
반면 하지만 여러 오브젝트들의 동시에 어떤 이벤트를 받고, 이를 모두 반영해야하는 경우, 📝 참고 |
No description provided.
The text was updated successfully, but these errors were encountered: