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@:");
您可以在 Objective C 运行时获得更多详细信息 文档.
You can get more details in the Objective C runtime documentation.
这篇关于Objective-C 中的拦截方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!