iPhone通知导致"unrecognized selector sent to instance..."的错误

14

简单来说,我在ClassA(在viewDidLoad中)注册以下的NSNotification监听器:

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

我在ClassA.h中声明了选择器:

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

实现过程如下:

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

tableView:didSelectRowAtIndexPath:方法中的ClassB类中,我有以下代码:

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

最终出现了一个错误消息:

"向实例发送了未识别的选择器"

在调用playSong方法之前。

能否有人在这里帮我解决?当我从一个控制器发布通知到另一个控制器时,我忘了什么吗?

1个回答

41

如果您的@selector需要带有参数,那么它需要一个:字符:

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

ClassA的实例不响应playSong选择器,但它们会响应playSong:选择器。


做到了。谢谢,伙计,这么小的细节 :-) 最后一个问题:如果我想指定选择器要采取哪种类型的对象,该怎么写语法?(object:nil),其中nil应该是定义。 - esbenr
@esbenr 当然可以,在“object”参数中传入任何你想要的内容。 - Jacob Relkin
在我的情况下,症状是相同的,但原因却是相反的。我在一个没有参数的方法的选择器上使用了 :。在我的情况下,去掉 : 就解决了问题。 - PassKit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接