Using NSNotificationCenter - posting a notification


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1.  
  2. Mutliple observers can be notified of events.
  3.  
  4. notification sent by a specific object...
  5. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFooHappened:) name:MyFooNotification object:foo];
  6.  
  7. set object to nil to receive notifications of that name sent by ANY object.
  8. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myFooHappened:) name:MyFooNotification object:nil];
  9.  
  10. Format for myFooHappened is..
  11. -(void) myFooHappened:(NSNotification*)note {
  12. // [note name] - name of notification [note object] - sender
  13.  
  14. // [note userInfo] is an NSDictionary of key-value pairs filled by the sender.
  15. }
  16.  
  17. Note: notifications are posted on the SAME THREAD as they were posted.
  18.  
  19. MUST unregister from all notifications in your dealloc
  20. -(void) dealloc
  21. [[NSNotificationCenter defaultCenter] removeObserver:self];
  22. }
  23.  
  24. Posting a notification..
  25. Define a constant for the name of the notification..
  26. in .h
  27. extern NSString* const MyFooNotification;
  28.  
  29. in .m
  30. NSString* const MyFooNotification = @"MyFooNotification";
  31.  
  32. -(void) postFoo {
  33. [[NSNotificationCenter defaultCenter] postNotificationName:MyFooNotification object:self userInfo:[NSDictionary ...]];

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.