Are selectors in Objective-C just another way to send a message to an object?

后端 未结 5 997
误落风尘
误落风尘 2020-12-08 17:39

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.

5条回答
  •  醉话见心
    2020-12-08 18:37

    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").)

    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].
    

提交回复
热议问题