개요
- 객체는
addObserver()
를 통해 notification center에 notification을 수신할 수 있도록 등록한다. - 등록하면 객체는 observer가 되는데, 이때 어떤 notification을 수신할 지 명시해주어야 하며, 따라서 여러 가지의 notification을 수신하려면
addObserver()
를 여러 번 호출해야 한다. - 앱에는 기본적으로
default
notification center가 존재하며(싱글톤), 특정 notification을 관리(발행, 수신)하기 위해 새로운 notification center를 생성할 수도 있다. - notification center를 통해, 앱의 한 쪽에서 다른 쪽으로 데이터를 전달할 수 있고, 객체들 간의 상호작용을 구현할 수 있다.
Notification
Notification Center를 통해 정보를 전달할 때 사용하게 되는 Struct.
아래와 같은 property들이 존재.
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]?
...
}
name: Notification.Name
Notification을 식별할 수 있게 하는 값. (NSNotification.Name
이라는 struct이다.)
아래와 같은 방식으로 extension을 이용해 추가하여 많이 사용한다.
extension Notification.Name {
static let test = Notification.Name("testNotification")
}
func postNotiTest() {
// 이제 아래와 같이 Notification을 생성하여 Publish(Post)할 수 있다.
let testNotification = Notification(name: Notification.Name.test)
// 만약 extension을 사용하지 않는다면 아래와 같이 생성한다.
let testNotification2 = Notification(name: Notification.Name("testNotification"))
NotificationCenter.default.post(testNotification)
}
object: Any?
addObserver()
를 통해 등록한 Observer들에게 보내고 싶은 데이터를 담으면 된다.
userInfo: [AnyHashable
: Any]?
이 Notification과 관련된 data(value), 혹은 object(객체)를 담을 수 있는 property.
NotificationCenter
예시 코드일 뿐, 실제로 작동하게 하려면 실행부를 함수 안으로 넣어줘야합니당
extension Notification.Name {
static let test = Notification.Name("testNotification")
}
class Poster {
func postTest() {
// Notification을 생성하고
let testNotification = Notification(name: Notification.Name.test, object: "testData")
// NotificationCenter에 Notification을 Post합니다
NotificationCenter.default.post(testNotification)
}
}
class Observer {
let observerName: String
init(observerName: String) {
self.observerName = observerName
// Observer라는 객체를 생성할 때, NotificationCenter에 객체를 Observer로 등록합니다.
// 이 때, selector는 objc 함수이며, Notification을 argument로 하고, Post된 Notification을 받은 후 실행된다.
NotificationCenter.default.addObserver(self, selector: #selector(afterReceive(noti: )), name: Notification.Name.test, object: nil, )
}
@objc func afterReceive(noti: Notification) {
guard let data = noti.object as? String else {
print("data fetching error")
return
}
print("\\(observerName) - Fetched Data: \\(data)")
}
}
let poster = Poster()
let observer1 = Observer(observerName: "1st")
let observer2 = Observer(observerName: "2nd")
poster.postTest()
/*
1st - Fetched Data: testData
2nd - Fetched Data: testData
*/