Objective-C中的拦截方法调用 [英] Intercept method call in Objective-C
问题描述
我可以在Objective-C中拦截方法调用吗?怎么样?
Can I intercept a method call in Objective-C? How?
修改: Mark Powell 的回答为我提供了部分解决方案,即 -forwardInvocation 方法. 但是文档指出-forwardInvocation仅在向对象发送没有相应方法的消息时才被调用.我希望在所有情况下都可以调用一种方法,即使接收者确实具有该选择器.
Mark Powell's answer gave me a partial solution, the -forwardInvocation method. But the documentation states that -forwardInvocation is only called when an object is sent a message for which it has no corresponding method. I'd like a method to be called under all circumstances, even if the receiver does have that selector.
推荐答案
您可以通过混淆方法调用来做到这一点.假设您想获取NSTableView的所有版本:
You do it by swizzling the method call. Assuming you want to grab all releases to NSTableView:
static IMP gOriginalRelease = nil;
static void newNSTableViewRelease(id self, SEL releaseSelector, ...) {
NSLog(@"Release called on an NSTableView");
gOriginalRelease(self, releaseSelector);
}
//Then somewhere do this:
gOriginalRelease = class_replaceMethod([NSTableView class], @selector(release), newNSTableViewRelease, "v@:");
You can get more details in the Objective C runtime documentation.
这篇关于Objective-C中的拦截方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!