본문 바로가기
#컴퓨터 과학 [Computer Science]/운영체제 (Operating System)

[OS - 🍎 macOS] DistributedNotificationCenter

by cy_mos 2023. 8. 30.
반응형
카테고리 게시글 작성 날짜 게시글 최근 수정 날짜 작성자
Operating System 2023.08.30. 22:08 2023.08.30. 22:08 Dev.Yang

 

📣 DistributedNotificationCenter

DistributedNotificationCenter는 macOS 운영체제에서만 사용되는 알림 구조의 일부로 다른 프로세스들에 알림을 전송 또는 수신을 할 수 있습니다. 또한 NSNotification의 확장 된 형태로 다른 작업의 객체로 브로드 캐스트 기능이 추가 되었습니다.

 

DistributedNotificationCenter의 주요 기능은 아래와 같습니다.


※ 알림 등록 및 제거 (Managing Observers)

 

DistributedNotificationCenter 알림 등록 및 제거 관련 예제 소스 코드는 아래와 같습니다.

 

@objc func receive(_ notification: Notification) {
        
        if let info = notification.userInfo {
           print("Notification received with userInfo: \(info)")
        } else {
           print("Notification received!")
        }
 }

// 모든 앱들 사이에 공유되는 기본 distributed notification center를 반환합니다.
let defaults = DistributedNotificationCenter.default()

// 지정 된 NSNotification.Name에 등록 된 알림 옵저버를 등록합니다.
defaults.addObserver(self, selector: #selector(receive), name: NSNotification.Name("StringUserInfo"), object: nil)

// 지정 된 NSNotification.Name에 등록 된 알림 옵저버를 제거합니다.
defaults.removeObserver(self, name: NSNotification.Name("StringUserInfo"), object: nil)

 

추가적으로 NSObjectProtocol 통하여 DistributedNotificationCenter 사용하는 방법에 대한 예제 소스 코드는 아래와 같습니다.

 

var observers = [NSObjectProtocol]()

// 모든 앱들 사이에 공유되는 기본 distributed notification center를 반환합니다.
let dnc = DistributedNotificationCenter.default()
        
let o1 = dnc.addObserver(forName: NSNotification.Name("StringUserInfo"), object: nil, queue: OperationQueue.main) { n in
    print("Can receive")
    print(n)
}
observers.append(o1)

let o2 = dnc.addObserver(forName: NSNotification.Name("URLUserInfo"), object: nil, queue: OperationQueue.main) { n in
    print("Cannot receive")
    print(n)
}
observers.append(o2)

 

알림 전송 (Posting Notifications)

 

DistributedNotificationCenter 알림 전송 관련 예제 소스 코드는 아래와 같습니다.

 

// 모든 앱들 사이에 공유되는 기본 distributed notification center를 반환합니다.
let dnc = DistributedNotificationCenter.default()
        
// 지정 된 NSNotification.Name에 알림을 전송합니다. (String)
dnc.postNotificationName(NSNotification.Name("StringUserInfo"), object: nil, userInfo: ["value": "hogehoge"], deliverImmediately: true)

// 지정 된 NSNotification.Name에 알림을 전송합니다. (URL)
dnc.postNotificationName(NSNotification.Name("URLUserInfo"), object: nil, userInfo: ["value": URL(string: "https://www.google.com")!], deliverImmediately: true)

🚀 REFERENCE

반응형

댓글