seong_hye, the developer

Swift) NotificationCenter이란? 본문

IOS

Swift) NotificationCenter이란?

seong_hye 2022. 7. 26.

 

📘 Swift : NotificationCenter


🔹 NotificationCenter 란?

iOS에서 컴포넌트 간 메시지를 전달하는 이벤트 브로드캐스팅 시스템이다.

~> 앱 내부에서 **누군가 어떤 일을 했음을 여러 객체에 알려줄 수 있는 구조**를 제공함

Swift에서 ViewController나 Model끼리 의존성없이 통신할 수 있게 해주는 중요한 도구

 

객체간의 직접 참조 없이도 메시지를 전달할 수 있게 해주는 옵저버 패턴 구현체

- 발신자(Post) : 어떤 이벤트가 발생했음을 알림

- 수신자(Observer) : 특정 알림을 구독하고, 발생 시 자동으로 호출됨 


🔹 사용 구조

✅ UIKit의 경우

// 1. 알림 이름 정의
extension Notification.Name {
	static let dataUpdated = Notification.Name("dataUpdated")
}


class MainViewController: UIViewController {
    ...
    // 2. 알림 수신자(Observer) 등록
	NotificationCenter.default.addObserver(
		self,
    	selector: #selector(handleUpdate),
    	name: .dataUpdated,
    	object: nil
	)
    
	// 4. 실제 처리 메서드
	@objc func handleUpdate(_ notification: Notification) {
		// 처리할 내용
	}
    ...
}

class SettingViewController: UIViewController {
	...
    @objc func change(_sender: ..) {
   		 // 3. 알림 발생(post)
		NotificationCenter.default.post(
			name: .dataUpdated,
    		object: nil
		)
    }
    ...
}

📌 요약 흐름

1. SettingViewController에서 post(name:useInfo:) 사용

2. MainViewController는 addObserver(...)로 알림 구독

3. 알림 발생 시 @objc 메서드가 실행 -> UI 갱신

 

 

✅ SwiftUI의 경우

// 1. 알림 이름 정의
extension Notification.Name {
	static let dataUpdated = Notification.Name("dataUpdated")
}

struct MainView: View {
    ...
    // 2. 알림 수신자(Observer) 등록
	private let notificationName = Notification.Name.dataUpdated
    
	// 4. 실제 처리 메서드
	.onReceive(NotificationCeter.default.publisher(for: notificationName)) {notification in
    	// 처리할 내용
    }
    ...
}

struct SettingView: View {
	...
    .onChange(of: ..) { newValue in
    	NotificationCenter.default.post(
        	name: .dataUpdated,
            object: nil,
            userInfo: [...:..]
        )
    }
    ...
}

🔹 수신자 해제 (removeObserver)

iOS 9 이상에서는 대부분 자동으로 해제되지만, 직접 해제하는 것이 안전함

deinit {
	NotificationCenter.default.removeObserver(self)
}

🔹 주의할 점

- Notification.Name은 상수로 미리 정의하여 오타를 방지하는 것이 좋음

- object: 를 지정하면 특정 객체에서 보낸 알림만 필터링할 수 있음

- userInfo를 통해 여러 데이터를 딕셔너리로 전달할 수 있음

- 강한 참조 순환에 주의 (self 캡처)


 

Comments