Programing

Cocoa 사용자 정의 알림 예제

crosscheck 2020. 11. 11. 08:00
반응형

Cocoa 사용자 정의 알림 예제


누군가 사용자 정의 알림, 실행 방법, 구독 및 처리 방법과 함께 Cocoa Obj-C 객체의 예를 보여줄 수 있습니까?


@implementation MyObject

// Posts a MyNotification message whenever called
- (void)notify {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}

// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
  NSLog(@"Got notified: %@", note);
}

@end

// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];

자세한 내용은 NSNotificationCenter 설명서를 참조하십시오 .


1 단계:

//register to listen for event    
[[NSNotificationCenter defaultCenter]
  addObserver:self
  selector:@selector(eventHandler:)
  name:@"eventType"
  object:nil ];

//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
    NSLog(@"event triggered");
}

2 단계:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];

객체가 할당 해제되면 알림 (관찰자)을 등록 취소해야합니다. Apple 문서에는 "알림을 관찰하는 객체가 할당 해제되기 전에 알림 센터에 알림 전송을 중지하도록 지시해야합니다."라고 말합니다.

로컬 알림의 경우 다음 코드가 적용됩니다.

[[NSNotificationCenter defaultCenter] removeObserver:self];

그리고 분산 된 알림의 관찰자 :

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];

참고 URL : https://stackoverflow.com/questions/842737/cocoa-custom-notification-example

반응형