Przykład Niestandardowego Powiadomienia Cocoa

Czy ktoś mógłby mi pokazać przykład obiektu Cocoa Obj-C, z niestandardowym powiadomieniem, jak go odpalić, subskrybować i obsługiwać?

Author: Martin Algesten, 2009-05-09

3 answers

@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];

Aby uzyskać więcej informacji, zobacz dokumentację NSNotificationCenter .

 81
Author: Jason Coco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-05-09 05:25:07

Krok 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");
}

Krok 2:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];
 45
Author: mracoker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-22 13:34:30

Pamiętaj o wyrejestrowaniu powiadomienia (obserwatora), gdy twój obiekt jest dealokowany. Dokumentacja Apple stwierdza: "zanim obiekt Obserwujący powiadomienia zostanie dealokowany, musi powiadomić Centrum powiadomień, aby zaprzestało wysyłania powiadomień".

Dla powiadomień lokalnych obowiązuje następny kod:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Oraz dla obserwatorów rozproszonych zgłoszeń:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
 5
Author: Grigori A.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-10 16:18:22