Posted By

magickaito on 03/29/11


Tagged

objectivec


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

Tintenklecks
cnathan
goliatone


Dispatch and Receive events in ObjectiveC


 / Published in: Objective C
 

thanks to http://stackoverflow.com/questions/2191594/how-to-send-and-receive-message-through-nsnotificationcenter-in-objective-c

  1. @implementation TestClass
  2.  
  3. - (void) dealloc
  4. {
  5. // If you don't remove yourself as an observer, the Notification Center
  6. // will continue to try and send notification objects to the deallocated
  7. // object.
  8. [[NSNotificationCenter defaultCenter] removeObserver:self];
  9. [super dealloc];
  10. }
  11.  
  12. - (id) init
  13. {
  14. self = [super init];
  15. if (!self) return nil;
  16.  
  17. // Add this instance of TestClass as an observer of the TestNotification.
  18. // We tell the notification center to inform us of "TestNotification"
  19. // notifications using the receiveTestNotification: selector. By
  20. // specifying object:nil, we tell the notification center that we are not
  21. // interested in who posted the notification. If you provided an actual
  22. // object rather than nil, the notification center will only notify you
  23. // when the notification was posted by that particular object.
  24.  
  25. [[NSNotificationCenter defaultCenter] addObserver:self
  26. selector:@selector(receiveTestNotification:)
  27. name:@"TestNotification"
  28. object:nil];
  29.  
  30. return self;
  31. }
  32.  
  33. - (void) receiveTestNotification:(NSNotification *) notification
  34. {
  35. // [notification name] should always be @"TestNotification"
  36. // unless you use this method for observation of other notifications
  37. // as well.
  38.  
  39. if ([[notification name] isEqualToString:@"TestNotification"])
  40. NSLog (@"Successfully received the test notification!");
  41. }
  42.  
  43. @end
  44.  
  45. ... somewhere else in another class ...
  46.  
  47. - (void) someMethod
  48. {
  49. // All instances of TestClass will be notified
  50. [[NSNotificationCenter defaultCenter] postNotificationName:@"TestNotification" object:self];
  51. }

Report this snippet  

You need to login to post a comment.