什么是@selector? [英] What actually is a @selector?
问题描述
有一些函数作为参数@selector(methodName)。我使用NSLog找出@selector是什么,它返回一个整数。它看起来像一个PID,但是当我运行ps ax无法找到PID。这个整数代表什么,为什么我们必须一直使用@selector,而不是只传递方法名?
There are some functions which take as an argument @selector(methodName). I used NSLog to find out what @selector is, and it returns an integer. It looks like a PID, but when I ran ps ax that PID could not be found. What does that integer represent and why do we have to use @selector all the time instead of just passing the method name?
推荐答案
@selector()
是一个编译器指令,将圆括号内的任何内容转换为 SEL
。 A SEL
是表示方法名称的类型,但不是方法实现。 (为了你需要一个不同的类型,可能是一个 IMP
或方法
SEL
被实现为 char *
,但是依赖于这种行为不是一个好主意。如果你想检查你有没有 SEL
,最好的方法是把它变成一个 NSString *
像这样:
@selector()
is a compiler directive to turn whatever's inside the parenthesis into a SEL
. A SEL
is a type to indicate a method name, but not the method implementation. (For that you'd need a different type, probably an IMP
or a Method
) Under-the-hood, a SEL
is implemented as a char*
, although relying on that behavior is not a good idea. If you want to inspect what SEL
you have, the best way to do it is to turn it into an NSString*
like this:
NSLog(@"the current method is: %@", NSStringFromSelector(_cmd));
(假设你知道 _cmd
的每个方法调用的隐藏参数,并且是对应于当前方法的 SEL
(Assuming you know that _cmd
is one of the hidden parameters of every method call, and is the SEL
that corresponds to the current method)
a href =http://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Selector.html =nofollow noreferrer> Objective-C语言指南有更多关于这个主题的信息。
The Objective-C Programming Language Guide has much more information on the subject.
这篇关于什么是@selector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!