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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSIncation 是一个用于将方法调用包装在对象中的类。 您可以设置选择器(方法签名),按索引设置参数。 然后,您可以设置目标并调用invoke来触发调用,或者保留目标未设置并在某种循环中使用invokeWithTarget:在许多对象上调用它。
我认为它的工作原理有点像这样:
或者,如果您不想将调用对象传递到此方法中,您可以使用 SEL 类型来接受选择器(方法签名)。
然后将选择器分配给调用对象,以便在对象上调用它。
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:
Or if you dont want to pass invocation objects into this method you can use the SEL type to accept a selector (method signature).
Then assign the selector to an invocation object in order to call it on objects.
或者,如果您使用
fooWithMethod:(SEL)selector
方法,只需对其执行[myObject PerformSelector:selector]
(如果它没有其他参数)。请参阅 NSObject 了解详细信息 。
Or if you're using the
fooWithMethod:(SEL)selector
approach, just do[myObject performSelector:selector]
on it, if it has no other arguments.See NSObject for details.
如前所述,您可以传递要调用的方法的选择器。 使用选择器有不同的方式来实际调用该方法:
NSInitation
对象objc_msgSend
或objc_msgSend_stret
IMP
您可以使用methodForSelector:
获得该方法的其中一个,使用哪一个实际上取决于具体情况。 如果性能并不重要,如果您需要传入 0、1 或 2 个对象,我会继续使用 1。 如果
performSelector:...
方法不匹配,我会选择 2 或 3。由于设置NSInitation
对象需要大量样板代码,所以我更喜欢 3 ,但我想这是个人选择的问题,除非存在性能问题。如果这些方法调用的性能很重要,我会使用 3 或 4。除非您可以缓存
IMP
,否则 3 应该更快。 但根据您的代码,这可能不可行或没有真正帮助。 因此,在这里您必须分析代码并查看哪一个更适合您。As said before you can pass the selector of the method you want to call. Using a selector there are different ways to actually call the method:
NSObject
sperformSelector:
,performSelector:withObject:
andperformSelector:withObject:withObject:
methodsNSInvocation
objectobjc_msgSend
orobjc_msgSend_stret
IMP
of that method which you can get usingmethodForSelector:
Which one to use really depends on the situation. If the performance is not critical I’d go ahead with 1 if you need to pass in 0, 1 or 2 objects. If the
performSelector:...
methods don’t match I’d go with 2 or 3. Since setting up anNSInvocation
object requires a lot of boilerplate code I prefer 3, but I guess that’s a matter of personal choice, unless there are performance issues.If the performance of those method calls does matter I’d use 3 or 4. 3 should be faster unless you can cache the
IMP
s. But depending on your code this may not be feasible or doesn’t really help. So here you must profile the code and see which one is better for you.