2

Trying to get one ViewController to communicate with another through standard Cocoa Notifications.

Wrote a simple test case. In my initial VC I add the following to viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self 
 selector: @selector(mesageReceived:)
 name:@"test.channel.pw" object:nil];

I add the following method:

- (void)mesageReceived:(NSNotification *)notif
{
    NSString *text = (NSString *)notif;    
}

I then segue to a VC which has the following added to its viewDidLoad:

  NSString *test = @"someText";
 [[NSNotificationCenter defaultCenter]
     postNotificationName:@"test.channel.pw" object:test];

When I run it, the notification works - the messageReceived method is called - but the value of text is "test.channel.pw", not "someText" as I expected.

What is going on here, and what is the correct syntax for passing a reference to a class instance using notifications?

Daniyar
  • 2,975
  • 2
  • 26
  • 39
Peter Webb
  • 671
  • 4
  • 14
  • possible duplicate of [How to pass object with NSNotificationCenter](http://stackoverflow.com/questions/7896646/how-to-pass-object-with-nsnotificationcenter) – Idrees Ashraf Sep 04 '15 at 12:08

4 Answers4

0

You need to pass your data using userInfo dictionary.

Change the notification passing code like:

[[NSNotificationCenter defaultCenter] postNotificationName:@"test.channel.pw" object:nil userInfo:[NSDictionary dictionaryWithObject:@"someText" forKey:@"dataKey"]];

And change the receiver method like:

- (void)mesageReceived:(NSNotification *)notif
{
    NSString *text = [[notif userInfo] objectForKey:@"dataKey"];    
}
Midhun MP
  • 103,496
  • 31
  • 153
  • 200
0

Try NSString *text = (NSString *)[notif object];.

Phillip Mills
  • 30,888
  • 4
  • 42
  • 57
0

By this

-(void)someMethod{
  NSDictionary *postDict = @{@"Key":[NSNumber numberWithFloat:17.0]};
[[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:postDict];
}

Some other class

-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter]postNotificationName:@"myNotification" object:nil userInfo:postDict];
}
-(void)valueForNotification:(NSNotification *)notification{
NSDictionary *dict = [notification userInfo];
NSLog(@"%@",[dict objectForKey:@"Key"]); //prints out 17.0
}
Saheb Roy
  • 5,899
  • 3
  • 23
  • 35
0

You need to pass only NSDictionary object in NSnotificationCenter. Through NSDictionary you can pass any data and then you need to parse once received.

Idrees Ashraf
  • 1,363
  • 21
  • 38