是否可以在Objective-C中将方法作为参数传递? [英] Is it possible to pass a method as an argument in Objective-C?
问题描述
我有一个方法,该方法因内部的单个方法调用而异,我想将其变化的方法/方法的签名作为参数传递...在Objective C中是否可行?有什么希望?
I have a method that varies by a single method call inside, and I'd like to pass the method/signature of the method that it varies by as an argument... is this possible in Objective C or is that too much to hope for?
推荐答案
NSInvocation是用于在对象中包装方法调用的类.您可以设置选择器(方法签名),按索引设置参数.然后,您可以设置目标并调用invoke来触发该调用,或者不设置目标并在某种循环中使用invokeWithTarget:在许多对象上调用它.
NSInvocation is a class for wrapping up a method calls in an object. You can set a selector (method signature), set arguments by index. You can then set a target and call invoke to trigger the call, or leave the target unset and use invokeWithTarget: in a loop of some sort to call this on many objects.
我认为它的工作原理如下:
I think it works a little like this:
NSInvocation *inv = [[NSInvocation alloc] init];
[inv setSelector:@selector(foo:bar:)];
[inv setArgument:123 atIndex:0];
[inv setArgument:456 atIndex:1];
for (MyClass *myObj in myObjects) {
[inv invokeWithTarget:myObj];
}
或者,如果您不想将调用对象传递给此方法,则可以使用SEL类型来接受选择器(方法签名).
Or if you dont want to pass invocation objects into this method you can use the SEL type to accept a selector (method signature).
-(void)fooWithMethod:(SEL)selector;
然后将选择器分配给调用对象,以便在对象上对其进行调用.
Then assign the selector to an invocation object in order to call it on objects.
这篇关于是否可以在Objective-C中将方法作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!