Alguém pode me mostrar um exemplo de um object Cocoa Obj-C, com uma notificação personalizada, como dispará-lo, assiná-lo e tratá-lo?
@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];
Para mais informações, consulte a documentação do NSNotificationCenter .
Passo 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"); }
Passo 2:
//trigger event [[NSNotificationCenter defaultCenter] postNotificationName:@"eventType" object:nil ];
Certifique-se de cancelar o registro de notificação (observador) quando o object for desalocado. A documentação da Apple declara: “Antes que um object que esteja observando notifications seja desalocado, ele deve informar ao centro de notifications para parar de enviar notifications”.
Para notifications locais, o próximo código é aplicável:
[[NSNotificationCenter defaultCenter] removeObserver:self];
E para observadores de notifications distribuídas:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];