본문 바로가기
IT/Swift

Swift의 NotificationCenter: 메모리 관리를 위한 효율적인 이벤트 전달

by bamcong 2025. 3. 13.
728x90
반응형

안녕하세요. 이번 포스팅에서는 Swift에서 NotificationCenter를 어떻게 활용할 수 있는지에 대해 상세히 살펴보겠습니다. NotificationCenter는 두 개 이상의 객체 간의 통신을 쉽게 만들어주는 강력한 도구입니다. 예를 들어, UI 요소가 특정 이벤트에 반응해야 할 때 유용하게 사용할 수 있습니다.

NotificationCenter란?

NotificationCenter는 iOS 및 macOS의 Foundation 프레임워크에서 제공하는 객체로, 하나의 객체가 발생시킨 이벤트를 다른 여러 객체가 듣고 처리할 수 있도록 해줍니다. 이를 통해 객체 간의 강한 결합을 방지하고, 느슨한 결합으로 메모리를 효율적으로 관리할 수 있습니다.

예를 들어, 여러분이 초콜릿 공장을 운영한다고 가정해 봅시다. 생산하는 과정에서 초콜릿이 만들어질 때마다 여러 기계들이 이를 감지해야 합니다. 여기에 NotificationCenter를 사용하면 쉽게 이벤트를 전파할 수 있습니다.

Swift NotificationCenter

NotificationCenter 사용 방법

1. Notification 정의

먼저, Notification을 정의합니다. 원하는 Notification 이름을 상수로 선언합니다.

let chocolateMadeNotification = Notification.Name("chocolateMade")

2. Observer 추가

이제 NotificationCenter에 Observer를 추가하여 특정 Notification이 발생했을 때 어떤 작업을 할지를 정의합니다.

NotificationCenter.default.addObserver(self, selector: #selector(handleChocolateMade), name: chocolateMadeNotification, object: nil)

@objc func handleChocolateMade(notification: Notification) {
    print("초콜릿이 만들어졌습니다!")
}

3. Notification 전송

이제 초콜릿이 만들어질 때마다 Notification을 전송합니다.

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

4. Observer 제거

NotificationCenter에 Observer를 추가한 후, 더 이상 필요하지 않을 경우에는 Observer를 제거해야 메모리 누수를 방지할 수 있습니다.

NotificationCenter.default.removeObserver(self, name: chocolateMadeNotification, object: nil)

전체 예제 코드

아래는 NotificationCenter를 활용한 전체 코드 예제입니다.

import UIKit

class ChocolateFactory {
    func makeChocolate() {
        // 초콜릿을 만드는 로직
        NotificationCenter.default.post(name: chocolateMadeNotification, object: nil)
    }
}

class Worker {
    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleChocolateMade), name: chocolateMadeNotification, object: nil)
    }

    @objc func handleChocolateMade(notification: Notification) {
        print("초콜릿이 만들어졌습니다!")
    }
}

let factory = ChocolateFactory()
let worker = Worker()
factory.makeChocolate() // "초콜릿이 만들어졌습니다!"를 출력합니다.

위의 코드를 실행하면, 생산 공장에서 초콜릿이 만들어질 때마다 Worker 객체가 알림을 받아 해당 이벤트를 처리하는 모습을 볼 수 있습니다.

NotificationCenter의 장점

NotificationCenter를 사용하면 객체 간의 의존성을 줄일 수 있습니다. 이를 통해 나중에 코드의 유지보수와 변경 작업이 쉬워집니다. 또한, 여러 개의 객체가 동일한 Notification을 수신하여 각기 다른 반응을 할 수 있게 함으로써, 다양한 이벤트 패턴을 구현하기 쉽게 됩니다.

이처럼 NotificationCenter는 효율적인 이벤트 전달과 객체 간의 느슨한 결합을 통해 소프트웨어 설계를 더 나은 방향으로 이끌 수 있습니다.

마무리

이번 포스팅을 통해 Swift의 NotificationCenter에 대한 기본 개념과 실용적인 예제를 제공하였습니다. 다양한 상황에 적용해 보시고, 객체 간의 통신을 효율적으로 관리해 보세요!

 

2025.02.27 - [IT/Swift] - 스위프트 인터페이스 스토리보드로 Hello World 앱 만들기

2025.02.27 - [IT/Swift] - Xcode 사용법: 애플 개발의 시작점

2025.03.11 - [IT/Swift] - Swift로 블루투스 UUID 찾고 연결하기

728x90
반응형