0Pricing
Swift Academy · 강의

알림 게시와 관찰

앱 전체에서 이벤트를 보내고 받습니다.

알림 게시와 관찰은(는) CoddyKit의 무료 Swift Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Swift Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

NotificationCenter

NotificationCenter는 알림을 브로드캐스트하는 방식입니다. App의 한 부분이 알림을 게시하면 여러 관찰자가 반응할 수 있으며, 보낸 쪽과 받는 쪽은 서로를 알 필요가 없습니다.

기본 센터

대부분의 코드는 NotificationCenter.default를 사용합니다. 이는 프로세스 전체에서 알림을 전달하는 공유 센터입니다.

import Foundation

let center = NotificationCenter.default
print("Using the default notification center")

알림 이름 정의하기

알림은 Notification.Name으로 식별합니다. 상수를 정의하면 오타를 방지하고 이름을 한곳에서 관리할 수 있습니다.

import Foundation

extension Notification.Name {
    static let dataUpdated = Notification.Name("dataUpdated")
}
print("Defined a notification name")

알림 게시하기

post(name:object:)는 알림을 브로드캐스트합니다. object는 보통 sender이거나 nil입니다.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("ping")
center.post(name: name, object: nil)
print("Posted a notification")

관찰자 추가하기(클로저)

블록 기반 addObserver(forName:object:queue:using:)는 알림이 발생할 때마다 클로저를 실행하고 token을 반환합니다.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("ping")
let token = center.addObserver(forName: name, object: nil, queue: .main) { _ in
    print("Observer fired")
}
center.post(name: name, object: nil)
_ = token

셀렉터 기반 관찰자

고전적인 API는 대상과 #selector를 사용합니다. 메서드는 Notification 인수를 받습니다.

import Foundation

class Watcher: NSObject {
    func start() {
        NotificationCenter.default.addObserver(
            self, selector: #selector(handle(_:)),
            name: Notification.Name("ping"), object: nil)
    }
    @objc func handle(_ n: Notification) { print("Handled") }
}
Watcher().start()

알림 받기

관찰자 클로저 또는 메서드는 이름, 객체, userInfo를 담은 Notification 값을 받습니다.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("event")
_ = center.addObserver(forName: name, object: nil, queue: nil) { note in
    print("Got: \(note.name.rawValue)")
}
center.post(name: name, object: nil)

일대다 브로드캐스트

여러 관찰자가 같은 이름의 알림을 listen할 수 있습니다. 한 번의 post가 모든 관찰자에게 알립니다.

import Foundation

let center = NotificationCenter.default
let name = Notification.Name("refresh")
_ = center.addObserver(forName: name, object: nil, queue: nil) { _ in print("A") }
_ = center.addObserver(forName: name, object: nil, queue: nil) { _ in print("B") }
center.post(name: name, object: nil)

객체로 필터링하기

nil이 아닌 object를 addObserver에 전달하면 sender가 게시한 알림에 대해서만 관찰자가 실행되도록 필터링합니다.

import Foundation

let center = NotificationCenter.default
let sender = NSObject()
let name = Notification.Name("scoped")
_ = center.addObserver(forName: name, object: sender, queue: nil) { _ in
    print("Only from sender")
}
center.post(name: name, object: sender)

시스템 알림

시스템은 키보드 이벤트나 앱 수명 주기 이벤트처럼 다양한 기본 제공 알림을 게시하며, 이러한 알림도 같은 방식으로 관찰합니다.

import Foundation

// e.g. UIApplication.didEnterBackgroundNotification on iOS
let custom = Notification.Name("appReady")
_ = NotificationCenter.default.addObserver(forName: custom, object: nil, queue: nil) { _ in
    print("App ready")
}

사용할 시점

NotificationCenter는 sender와 수신자가 서로 분리되어 있어야 하는 전역 일대다 이벤트에 적합합니다. 긴밀한 일대일 연결에는 delegate가 더 명확한 경우가 많습니다.

import Foundation

// Broadcast a global event many parts of the app care about.
let name = Notification.Name("userLoggedOut")
NotificationCenter.default.post(name: name, object: nil)
print("Broadcast logout")

빠른 확인

NotificationCenter.default.post(name:object:)는 무엇을 하나요?

복습

NotificationCenter.default는 sender와 수신자를 분리합니다. Notification.Name을 정의하고, 이를 post한 다음, 클로저나 셀렉터를 사용해 addObserver하여 반응합니다. 일대다 브로드캐스트와 객체 필터링을 지원합니다. 다음에는 userInfo로 데이터를 전달하는 방법을 살펴봅니다.

자주 묻는 질문

“알림 게시와 관찰” 강의는 무료인가요?

네 — “알림 게시와 관찰” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Swift Academy 강의 전체를 잠금 해제할 수 있습니다. Swift Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“알림 게시와 관찰”에서 뭘 배우나요?

앱 전체에서 이벤트를 보내고 받습니다. 브라우저에서 직접 실행하는 실습 코드로 Swift Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Swift Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Swift Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“알림 게시와 관찰” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Swift Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Swift Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 알림 게시와 관찰
  2. 알림 userInfo 페이로드
  3. 옵저버 안전하게 제거하기
  4. 옵저버 패턴의 대안
← Swift Academy(으)로 돌아가기