对于 Objective-C ...方法指针
我想设置一个方法调度表,我想知道是否可以在 Objective-C 中创建指向方法的指针(就像 C 中指向函数的指针)。 我尝试使用一些 Objective-C 运行时函数来动态切换方法,但问题是它会影响所有实例。
由于我对 Objective-C 非常陌生,因此非常感谢一个说明性的例子。
I want to setup a Method dispatch table and I am wondering if it is possible to create pointer to a method in Objective-C (like pointer to function in C). I tried to use some Objective-C runtime functions to dynamically switch methods but the problem is it will affect all instances.
As I am very new to Objective-C, an illustrated example would be highly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Objective-C 方法称为
选择器
,并由SEL
数据类型表示。 如果您的对象继承自NSObject
,您可以告诉它执行选择器(即调用方法),如下所示:这假设您定义了一个方法,例如:
选择器被分配给
SEL< /code> 数据类型通过
@selector
关键字,它采用您想要保留的方法的名称。 方法的名称是去掉所有参数的方法名称。 例如:将被引用为
@selector(doSomething:withParams:)
。Objective-C methods are called
selector
s, and are represented by theSEL
datatype. If your object inherits fromNSObject
, you can tell it to perform a selector (i.e. call a method) like thus:This assumes you have a method defined such as:
Selectors are assigned to
SEL
datatypes through the@selector
keyword, which takes the name of the method you would like to keep. The name of the method is the method name stripped of all arguments. For example:Would be referenced as
@selector(doSomething:withParams:)
.是的! 在 Objective-C 中,函数指针称为选择器。 如果您有这样定义的方法:
选择器的声明如下:
要对对象执行选择器,您可以使用:
或
选择器数据类型对于线程和计时器特别有用,您可以在其中分派线程并提供它您希望它调用的消息的选择器。 如果您需要创建选择器数组(或调度表),或者需要使用多个参数调用选择器,则可以使用 NSInitation 类。 它为选择器提供了一个包装器,并允许您指定实际参数。
您应该记住,Objective-C 已经基于完全动态的方法调度表。 听起来,如果您只需要对函数的引用,那么使用选择器维护函数指针将非常适合您。
Yes! In Objective-C, function pointers are called selectors. If you have a method defined like this:
The selector is declared like this:
To perform a selector on an object, you can use:
or
The selector data type is particularly useful for threads and timers, where you can dispatch a thread and provide it a selector to the message you'd like it to invoke. If you need to create an array of selectors (or a dispatch table), or if you need to invoke selectors with multiple parameters, you can use the NSInvocation class. It provides a wrapper for a selector and allows you to specify actual arguments.
You should keep in mind that Objective-C is already based on a fully dynamic method dispatch table. It sounds like maintaining function pointers using selectors will work fine for you if you just need a reference to a function, though.