Objective-C中的选择器? [英] Selectors in Objective-C?

查看:95
本文介绍了Objective-C中的选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我不确定我是否真的了解选择器.根据我的理解,它是方法的名称,您可以将其分配给类型为'SEL'的类,然后运行诸如responseToSelector之类的方法,以查看接收方是否实现了该方法.有人可以提供更好的解释吗?

First, I'm not sure I really understand what a selector is. From my understanding, it's the name of a method, and you can assign it to a class of type 'SEL' and then run methods such as respondToSelector to see if the receiver implements that method. Can someone offer up a better explanation?

第二,到此为止,我有以下代码:

Secondly, to this point, I have the following code:

NSString *thing = @"Hello, this is Craig";

SEL sel = @selector(lowercaseString:);
NSString *lower = (([thing respondsToSelector:sel]) ? @"YES" : @"NO");
NSLog (@"Responds to lowercaseString: %@", lower);
if ([thing respondsToSelector:sel]) //(lower == @"YES")
    NSLog(@"lowercaseString is: %@", [thing lowercaseString]);

但是,即使thing显然是一种NSString,并且应该响应小写字符串,但我无法获得'respondsToSelector'条件,以返回"YES" ...

However, even though thing is clearly a kind of NSString, and should respond to lowercaseString, I cannot get the 'respondsToSelector' conditional to return "YES"...

推荐答案

您必须非常注意方法名称.在这种情况下,方法名称仅是"lowercaseString",而不是"lowercaseString:"(请注意,不存在冒号).这就是为什么要返回NO的原因,因为NSString对象响应lowercaseString消息而不是lowercaseString:消息.

You have to be very careful about the method names. In this case, the method name is just "lowercaseString", not "lowercaseString:" (note the absence of the colon). That's why you're getting NO returned, because NSString objects respond to the lowercaseString message but not the lowercaseString: message.

您如何知道何时添加冒号?如果在调用消息名称时添加了一个冒号,则可以在该消息名称中添加一个冒号(如果使用一个参数,则会发生这种情况).如果它接受零个参数(lowercaseString就是这种情况),则不存在冒号.如果需要多个参数,则必须添加额外的参数名称及其冒号,如compare:options:range:locale:所示.

How do you know when to add a colon? You add a colon to the message name if you would add a colon when calling it, which happens if it takes one argument. If it takes zero arguments (as is the case with lowercaseString), then there is no colon. If it takes more than one argument, you have to add the extra argument names along with their colons, as in compare:options:range:locale:.

您还可以查看

You can also look at the documentation and note the presence or absence of a trailing colon.

这篇关于Objective-C中的选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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