何时使用带@selector的冒号 [英] When to use a colon with a @selector

查看:115
本文介绍了何时使用带@selector的冒号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始使用iPhone开发和Objective-C。

Just getting going with iPhone development and Objective-C.

昨天我试图在我的视图中添加Observer以获取通知,并且我一直收到此错误:

Yesterday I was trying to addObserver for a notification in a view of mine, and I kept getting this error:

unrecognized selector sent to instance

我追踪到了这样的事实:我需要在我的selector参数中包含尾部冒号:

I tracked it down to the fact that I needed to include the trailing colon to my selector argument:

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

今天,我认为我很聪明,因为在设置按钮的动作参数时,我记得我昨天的错误,将冒号添加到action参数中。 action参数采用@selector,就像设置NSNotification的观察者时的selector参数一样,所以我认为我做的是正确的。

Today, I thought I was clever because when setting up the action argument to a button, I remembered my mistake yesterday, and added the colon to the action argument. The action argument takes a @selector, just like the selector argument while setting up an observer for an NSNotification, so I figured I was doing the right thing.

但是,以下代码:

[self.callToActionButton addTarget:self action:@selector(nameOfMySelector:) forControlEvents:UIControlEventTouchUpInside];

我得到完全相同的错误:

I get the exact same error:

unrecognized selector sent to instance

给出了什么?为什么一个@selector需要一个尾随冒号而另一个不需要?我应该遵循哪些规则应该包含哪些内容以及什么时候应该停止,以及为什么我不能总是只做一个或另一个?

What gives? Why does one @selector require a trailing colon, and the other doesn't? What are the rules I should follow for when it should be included and when it should be left off, and why I can't I always just do one or the other?

谢谢!

推荐答案

正如boltClock所提到的,你所指的字符实际上是冒号。 @selector(方法) @selector(method:)之间的区别是方法签名。第二个变体需要传递一个参数。

As mentioned by boltClock, the character you are referring to is actually a colon. The difference between @selector(method) and @selector(method:) is the method signature. The 2nd variant expects a parameter to be passed.

@selector(method)期望方法: - (void)方法

@selector(方法:) 期望方法: - (void)方法:(id)someParameter

这篇关于何时使用带@selector的冒号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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