iphone notification results in “unrecognized selec

2019-03-24 19:07发布

问题:

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?

回答1:

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.