Objective-C中的选择器只是向对象发送消息的另一种方式吗? [英] Are selectors in Objective-C just another way to send a message to an object?
问题描述
Objective-C中的选择器是否只是向对象发送消息的另一种方式?我真的不明白为什么或如何使用它们.
Are selectors in Objective-C just another way to send a message to an object? I really don't understand why or how to use them.
推荐答案
它们不是向对象发送消息的另一种方法,它们是唯一的方法.例如,在[myView setValue:@"foo"]
中,setValue:
是选择器. (另一种不太方便的写相同方法的方法是objc_msgSend(myView, @selector(setValue:), @"foo")
.)
They aren’t another way to send a message to an object, they’re the only way. For example, in [myView setValue:@"foo"]
, setValue:
is a selector. (Another, less convenient way of writing the same thing is objc_msgSend(myView, @selector(setValue:), @"foo")
.)
正如伊恩·亨利(Ian Henry)所说,您可以使用SEL
值在运行时而不是编译时选择选择器.这是可可粉中的一项基本技术.用户界面通常使用目标/动作绑定连接到控制器,其中目标是对象,而动作是选择器.通常,您可以在笔尖中进行设置,但是也可以通过代码进行设置:
As Ian Henry says, you can use SEL
values to choose a selector at runtime instead of compile time. This is a fundamental technique in Cocoa; user interfaces are generally connected to controllers using target/action bindings, where the target is an object and the action is a selector. Normally you set this up in a nib, but you can also do it in code:
[myButton setTarget:myController];
[myButton setAction:@selector(buttonClicked:)]; // Clicking the button will now call [myController buttonClick:myButton].
这篇关于Objective-C中的选择器只是向对象发送消息的另一种方式吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!