“发送到实例的无法识别的选择器"Objective-C 中的错误 [英] "unrecognized selector sent to instance" error in Objective-C

查看:21
本文介绍了“发送到实例的无法识别的选择器"Objective-C 中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个按钮并为它添加了一个动作,但是一旦它被调用,我就得到了这个错误:

I created a button and added an action for it, but as soon as it invoked, I got this error:

-[NSCFDictionary numberButtonClick:]: unrecognized selector sent to instance
 0x3d03ac0 2010-03-16 22:23:58.811
 Money[8056:207] *** Terminating app
 due to uncaught exception
 'NSInvalidArgumentException', reason:'*** -[NSCFDictionary numberButtonClick:]:  unrecognized selector sent to instance 0x3d03ac0'

这是我的代码:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        UIButton *numberButton = [UIButton buttonWithType:UIButtonTypeCustom];        
        numberButton.frame = CGRectMake(10, 435, 46, 38);
        [numberButton setImage:[UIImage imageNamed:@"one.png"] forState:UIControlStateNormal];
        [numberButton addTarget:self action:@selector(numberButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview: numberButton]; 
    }
return self;
}

-(IBAction)numberButtonClick:(id)sender{
    NSLog(@"---");
}

推荐答案

好的,我必须在这里筹码.OP 动态创建了按钮.我有一个类似的问题,答案(经过几个小时的狩猎)非常简单,让我感到恶心.

OK, I have to chip in here. The OP dynamically created the button. I had a similar issue and the answer (after hours of hunting) is so simple it made me sick.

使用时:

action:@selector(xxxButtonClick:)

or (as in my case)

action:NSSelectorFromString([[NSString alloc] initWithFormat:@"%@BtnTui:", name.lowercaseString])

如果您在字符串末尾放置一个冒号 - 它将通过发送者.如果你不把冒号放在字符串的末尾,它就不会,如果接收器需要一个,它将得到一个错误.如果是动态创建事件名称,很容易漏掉冒号.

If you place a colon at the end of the string - it will pass the sender. If you do not place the colon at the end of the string it will not, and the receiver will get an error if it expects one. It is easy to miss the colon if you are dynamically creating the event name.

接收器代码选项如下所示:

The receiver code options look like this:

- (void)doneBtnTui:(id)sender {
  NSLog(@"Done Button - with sender");
}
 or
- (void)doneBtnTui {
  NSLog(@"Done Button - no sender");
}

像往常一样,总是错过明显的答案.

As usual, it is always the obvious answer that gets missed.

这篇关于“发送到实例的无法识别的选择器"Objective-C 中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆