14

To make it short, I'm registering the following NSNotification listener in ClassA (in viewDidLoad):

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playSong) name:@"playNotification" object:nil];

I have the selector declared in ClassA.h:

- (void)playSong:(NSNotification *) notification;

And implementation goes as follows:

- (void)playSong:(NSNotification *) notification {
    NSString *theTitle = [notification object]; 
    NSLog(@"Play stuff", theTitle);
}

In ClassB (in the tableView:didSelectRowAtIndexPath: method) I have:

NSInteger row = [indexPath row];
NSString *stuff = [playlistArray objectAtIndex:row];
[[NSNotificationCenter defaultCenter] postNotificationName:@"playNotification" object:stuff];

It all end up with an error message saying:

"unrecognized selector sent to instance"

before the playSong method is invoked.

Can anybody please help me out here? What am I forgetting when posting a notification from one controller to another?

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
esbenr
  • 1,356
  • 1
  • 11
  • 34

1 Answers1

41

Your @selector needs a : character if it is to take an argument:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playSong:) name:@"playNotification" object:nil];

Instances of ClassA do not respond to the playSong selector, but they do respond to the playSong: selector.

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
  • Did the trick. Thanks man, such a small detail :-) One last question: If i want to specify which type of object i want the selector to take, what are the syntax to do that? (object:nil) where nil should be the definition. – esbenr Dec 24 '10 at 10:57
  • @esbenr Sure, you can pass in whatever you like in the `object` parameter. – Jacob Relkin Dec 24 '10 at 16:14
  • In my case, the symptoms were the same, but the cause was the opposite. I had a `:` on my `selector` for a method with no arguments. In my case, removing the `:` fixed it. – PassKit Apr 23 '13 at 15:17