ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • NotificationCenter
    iOS 2019. 11. 27. 14:26

    Notification은 객체 간의 소통을 위해 사용되는 도구 중 하나이다.
    MVC 패턴에서 Controller는 View 또는 Model과 직접 커뮤니케이션 하지 않는 것이 바람직하다.
    Notification은 주로 Controller에서 Model의 상태 변화를 감지하는데 사용된다.
    (API 통신을 하는데 데이터를 받은 후 Controller에서 작업을 하고 싶다면??!)

     

    어떻게 작동하는가?

    Notification Center는 3개의 구성 요소로 이루어져 있다.

    • Listener (observer) : notifications를 감지
    • Sender : 필요할 때 notifications 를 보내주는 역할
    • itself : notification center 그 자체.

     

    작동 원리는 매우 간단하다.

    Observer가 관찰 시작 → 작업이 발생하면 Sender가 Post → Observer selector 실행

     

    Observers 등록하기

    addObserver(_:selector:name:object:)

    NotificationCenter.default.addObserver(
        self, // observer가 될 object
        selector: #selector(onDidReceiveData(_:)), // noti가 오면 실행할 함수
        name: .didReceiveData, // Noti의 이름
        object: nil // noti받을 대상. 지정하면 특정 sender에게만 notif를 받음 (optional)
    )

    Notification Name

    모든 Notification은 Notification.Name(" ") 와 같이 이름을 갖는데,

    apple이 저징해 놓은 noti처럼 좀 더 편하게 사용하고 싶다면 등록해서 사용할 수도 있다.

    extension Notification.Name {
        static let didReceiveData = Notification.Name("didReceiveData")
        static let didCompleteTask = Notification.Name("didCompleteTask")
        static let completedLengthyDownload = Notification.Name("completedLengthyDownload")
    }

    Notification default

    NotificationCenter의 default property는 말 그대로 기본이다. 앱의 keyboard와 같은 app의 기본 system notification 들이 등록되어 있다. 굳이 새로 만들 필요는 없지만 나만의 custom notification 도 만들 수 있다.

    remove observe

    observers는 deallocated 되기 전에 제거되어야 한다.

     

    Notification Post

    post(name:object:userInfo:)

    NotificationCenter.default.post(
        name: .didReceiveData, 
        object: nil
    )

    name property는 observers에서 관찰하는 Notification.Name과 완전히 동일하고

    observers에서 특정 sender만 notification을 받을 수 있으려면 post할 때 object를 등록해줘야 한다.

    userInfo: 는 비워둘 수 있는데, userInfo를 통해 데이터를 전달할 수 있다. [AnyHashable: Any]? 타입이므로 사용할 때는 원하는 타입으로 다운캐스트 해서 사용해야 한다.

    // on observers
    @objc func onDidReceiveData(_ notification: Notification)
    {
        if let data = notification.userInfo as? [String: Int]
        {
            for (name, score) in data
            {
                print("\(name) scored \(score) points!")
            }
        }
    }
    
    // on post
    let scores = ["Bob": 5, "Alice": 3, "Arthur": 42]
    
    NotificationCenter.default.post(
        name: .didReceiveData, 
        object: self, 
        userInfo: scores
    )

    참고

    Using Notification Center In Swift (How To) - LearnAppMaking

    'iOS' 카테고리의 다른 글

    round only specific corners  (0) 2019.12.06
    iOS) View rounded + shadow 구현하기  (1) 2019.12.05
    CGPoint, CGSize, CGRect  (0) 2019.11.26
    Apple Certification, .p8 .p12 .pem  (0) 2019.11.20
    나만의 String 만들기, NSMutableAttributedString  (0) 2019.10.14

    댓글

Designed by Tistory.