7

I saw a few examples about adding observer and handle in the same class, but what I want to know is if it's possible to add observer in first view controller and handle it in second view controller?

I want constantly send distance from first view controller and handle it in the 2nd one. The 2nd view controller added as a sub view: addSubview, addChildViewController.

It's something like broadcast in android.

Idan Moshe
  • 1,675
  • 4
  • 28
  • 65
  • Why wouldn't it? That's *exactly* the purpose of `NSNotificationCenter`. –  Jun 13 '13 at 06:33

2 Answers2

21

Yes it is possible. NSNotificationCenter works exactly in that way.

Firstly, you will have to register the listener in the first view controller as below.

-(void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(somethingHappens:) name:@"notificationName" object:nil];
}

-(void)somethingHappens:(NSNotification*)notification
{

}

Secondly, post the notification from the second view controller as below.

[[NSNotificationCenter defaultCenter] postNotificationName:@"notificationName" object:obj];

The system will broadcast the notification to all the listeners.

Abdurrahman Mubeen Ali
  • 1,331
  • 1
  • 13
  • 19
taffarel
  • 4,015
  • 4
  • 33
  • 61
  • I'm a little bit confused, I use 'postNotificationName' when I want to say 'all is ok, handle event', right? But 'somethingHappens' should be in 2nd view controller. Just to clarify which code should be in the correct controller. – Idan Moshe Jun 13 '13 at 06:47
  • 1
    if you want to send notification from viewcontroller A to viewController B , then you need to use postnotification from A view controller, and register the listener and handle it in B, every time when notification is posted somethingHappens method will be called automatically, since you register the listener to that method. – taffarel Jun 13 '13 at 06:51
  • thank you! solved my problem! – Felipe Xavier Dec 18 '15 at 09:57
  • can i send notification to all of controllers in my iOS app? – reza_khalafi Jan 20 '16 at 07:59
0

There is another way to do this (in case you want to let other view controllers know if a value of an object has changed). You can use KVO (Key-Value Observing): http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/KeyValueObserving/Articles/KVOBasics.html

Second Front
  • 81
  • 1
  • 1