Skip to content
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

iOS 앱에서 NotificationCenter를 사용하는 목적과 사용 방법을 설명해주세요. #27

Open
kmh5038 opened this issue Apr 27, 2024 · 1 comment
Assignees

Comments

@kmh5038
Copy link
Member

kmh5038 commented Apr 27, 2024

  • iOS 앱에서 NotificationCenter를 사용하는 목적과 사용 방법을 설명해주세요.
@kmh5038 kmh5038 self-assigned this Apr 27, 2024
@kmh5038
Copy link
Member Author

kmh5038 commented Apr 27, 2024

1. 정의

1-1. Notification

Notification 이름을 봤을때 무언가를 알리는 역활을 하는것으로 유추할 수 있습니다. 그것이 유저에게 무언가를 알려주는 알림이 아닌 앱 내에서 정보를 전하기 위해 알림을 방송한다라는 뜻입니다.

Notification은 NotificationCenter를 통해 전달되는 정보 단위인 구조체입니다. NotificationCenter를 설명할때 보통 우체국에 많이 비유하는데 Notification은 우체국에서 발송하는 편지라고 생각하시면 이해에 도움이되실겁니다.

내부는 name, object, userInfo로 구성되어 있습니다.

  • name: 전달하고자 하는 Notification의 이름(식별자)
  • object: 발송자가 옵저버에게 보내려고 하는 객체
  • userInfo: Notification과 관련된 값이나 객체의 저장소

1-2. NotificationCenter

NotificationCenter는 객체로부터 어떤 이벤트를 받아 자신에게 등록된(옵저버) 객체들에게 알림을 보내주는 객체입니다.
NotificationCenter는 싱글톤으로 구성되어 있어 사용자가 인스턴스를 만들지 않고 호출할 수 있습니다.
앱 내에서 공식적인 연결이 없는 두 개 이상의 컴포넌트들이 상호작용이 필요할때, 상호작용이 반복적으로 그리고 지속적으로 이루어져야 할 때, 일대다 또는 다대다 통신을 사용할때 주로 사용됩니다..


2. 사용 방법

NotificationCenter의 이해를 돕기위해 우체국과 우체부에 비교하여 흐름부터 설명하겠습니다.

2-1. NotificationCenter 흐름

  1. addObserver : NotificationCenter로부터 전달되는 소식을 들을거라고 구독을 합니다.
    (우체부는 우체국에게 '저는 해운대구 전담 우체부입니다'라고 등록을 합니다)

  2. event 발생 : 사용자가 버튼을 누르거나 텍스트 필드에 입력을 하는등 event가 발생했다.
    (최동호는 해운대구에 사는 김명현에게 편지를 썼습니다.)

  3. post : 객체가 NotificationCenter로 이벤트를 보내는 행위를 의미합니다.
    (최동호는 우체국에 편지를 부쳤습니다.)

  4. notify : 식별자에 해당하는 모든 옵저버에게 Notification을 전달합니다.
    (우체국은 해운대구 전담 우체부에게 해운대구로 가는 편지가 왔다고 전달해줍니다.)

  5. selector : Notification 객체의 정보를 사용하여 작업을 수행합니다.
    (해운대구 우체부가 편지를 배송합니다)


2-2. NotificationCenter 구현

title


import UIKit

class AViewController: UIViewController {

@IBOutlet weak var image: UIImageView!
@IBOutlet weak var text: UILabel!


override func viewDidLoad() {
    super.viewDidLoad()
}

// selector
@objc func changeImg(_ notification: Notification) {
    guard let letter = notification.object as? String else { return }
    guard let image = UIImage(systemName: "checkmark.seal.fill") else { return }
    self.text= letter
    self.image = image
}
  
// 화면이동 함수
@IBAction func goBVC(_ sender: Any) {
    guard let BviewController = self.storyboard?.instantiateViewController(identifier: "BViewController") as? BViewController else { return }

    //관찰자등록
    NotificationCenter.default.addObserver(
      self,
      selector: #selector(changeImg(_:)),
      name: NSNotification.Name("letter"),
      object: nil
    )
    self.navigationController?.pushViewController(BviewController, animated: false)
 }
}


import UIKit

class BViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    
    NotificationCenter.default.post(
      name: NSNotification.Name("letter"),
      object: "편지받았다.",
      userInfo: nil
    )
 }
}

  1. 화면A에 옵저버를 등록합니다(addObserber). 화면을 이동합니다.
  2. 화면B에 도착하면 화면A에 Notification을 보냅니다.
  3. 화면A는 Notification을 받자마자 정해진 행동(selector)을 합니다.
  4. 화면A로 돌아오면 정해진 행동이 완료되어있습니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant