써니쿠키의 IOS 개발일기

[swift] NotificationCenter 구현 본문

swift, Ios

[swift] NotificationCenter 구현

sunnyCookie 2022. 9. 7. 16:41

KVO로 구현한 데 이어서 같은 화면 내용을 노티피케이션센터를 이용해서 만들어보았다
텍스트필드에 내용을 적은 후 등록버튼을 누르면 밑에 있는 텍스트뷰에 똑같은 내용을 띄우는 코드이다.


( 보통 알림을 주는곳과 Observer가 서로 다른 타입에 만들어지지만 여기서는 ViewController Class 안에 모든걸 구현해보았다 )

노티피케이션 센터 구현은 아래 네가지를 차근차근 구현하면된다.

  1. POST: 노티피케이션센터에서 값 전달하기
  2. Observer 등록하기
  3. Observer가 실행할 함수 만들기
  4. Observer 제거하기

1. POST : 노티피케이션센터에서 값 전달하기

    func notificate(writedThing: String) {
        NotificationCenter.default.post(name: Notification.Name("writedThing"), object: nil, userInfo: ["myWriting": writedThing])
    }

NotificationCenter.default.post 를 설정해주면 이제 알림을 줄 것이라는 의미이다. 3가지 파라미터를 입력해 주어야 한다

  • name / object / userInfo
  • 1️⃣ name : 노티피케이션센터의 이름이다. 노티피케이션센터가 여러러개 일 때 어느센터의 값을 받을지 이름으로 식별할 수 있게 이름을 정해준다. Notification.Name 형식을 지켜야 한다. (extension이용으로 Notification.Name을 줄여서 쓰는 코드가 가능하다 (나중에해봐야지))
  • 2️⃣ object: 객체를 전달할때 사용하고, 없으면 nil 입력해준다.
  • 3️⃣ userInfo: 일반적으로 전달하고 싶은 정보를 userInfo 에 저장해서 전달한다. 딕셔너리와 같이 사용하면 된다. key 와 value 값으로 전달할 수 있고 받는 지점에서 해당 Key를 입력하면 Key에 해당하는 Value를 사용할 수 있다.

2. Observer 등록하기

NotificationCenter.default.addObserver(self, selector: #selector(receiveNoti), name: Notification.Name("writedThing"), object: nil)

NotificationCenter.default.addObserver 로 옵저버를 추가 한다.
4가지 파라미터를 입력해 주어야한다

  • observer / selector / name / object
  • 1️⃣ observer: 관찰자로 등록할 Object로 보통은 자기 자신이므로 self 를 쓴다.
  • 2️⃣ selector: 알림을 받았을 때 실행하는 메서드다. 이 메서드는 NSNotification의 인스턴스 를 파라미터로 받아야 한다.
  • 3️⃣ name: 옵저버에게 전달하기 위해 등록할 이름이다. post에서 지정해준 이름과 같아야 해당 알림을 받을 수 있다. nil일 때 이름이 알림배달의 기준이 되지 않는다.
  • 4️⃣ object: 옵저버에게 알림을 보내는 object이다. 이 발신자의 알림만 받겠다고 할 때 써주면된다. nil일 때 보낸사람 이름이 배달 기준이 되지 않는다.

3. observer가 실행할 함수 만들기

 @objc func receiveNoti(notification: Notification) {
        guard let writedThing = notification.userInfo?["myWriting"] as? String else { return }
        copyWriteField.text = writedThing
 }

우선 @objc 를 붙여줘야한다.
(NSObject 를 상속 받고 있기에 object-C에서 사용한다는 뜻이다)

파라미터로 Notification 을 넣어 주어야 한다.
그러면 notification 으로 userInfoobject 에 접근해서 값을 사용할 수 있다.
이 때 userInfo가 딕셔너리 이므로 옵셔널 바인딩이 필요하고 사용을 위해 다운 캐스팅이 필수이다.


4. Observer 제거하기

deinit {
        NotificationCenter.default.removeObserver(self)
    }

노티피케이션을 제거해주지 않으면 메모리에 계속 올라가 있게 되므로 꼭 해제해줘야한다.
나의 경우에는 함수가 끝나기전 마지막 코드로 deinit되도록 하였다.


전체 코드

class ViewController: UIViewController {
    @IBOutlet weak var writeField: UITextField!
    @IBOutlet weak var copyWriteField: UITextView!

    func notificate(writedThing: String) {
        NotificationCenter.default.post(name: Notification.Name("writedThing"), object: nil, userInfo: ["myWriting": writedThing])
    }

    @objc func receiveNoti(notification: Notification) {
        guard let writedThing = notification.userInfo?["myWriting"] as? String else { return }
        copyWriteField.text = writedThing
    }

    @IBAction func registerButtonOnTouched(_ sender: UIButton) {
        NotificationCenter.default.addObserver(self, selector: #selector(receiveNoti), name: Notification.Name("writedThing"), object: nil)
        guard let writedThing = writeField.text else { return }
        notificate(writedThing: writedThing)
        NotificationCenter.default.removeObserver(self)
    }
}

post 메서드 공식문서
NotificationCenter.default.addObserver 공식 문서
removeObserver 공식 문서

반응형
Comments