是否可以为Objective-C中的每个方法调用生成包装器?

时间:2019-04-02 06:39:48

标签: objective-c objective-c-runtime method-invocation method-swizzling

我有一个包含很多课程的项目。 我想在运行时记录每个选择器的调用(例如到stderr)。
我的主要要求是不更改现有代码,因此我不能只在每次调用开始时记录函数的参数。

如果在程序执行过程中调用了某种方法,例如

merge

我想用类似的东西替换它:

@implementation Class1

// ...

- (int)someFunc:(Class2*) a andClass3:(Class3*)b
{

}

// ...

@end 

有可能吗?

我已经读过方法混乱,KVO和转发消息。

我当前使用方法混乱的方法会导致无限递归:

- (int)someFuncWrapper:(Class2*) a andClass3:(Class3*)b
{
     NSLog(@"- (int)someFuncWrapper:a andClass3:b <= a=%@, ab=%@", a, b);
     return [someFunc: a andClass3:b];
}

恐怕在运行时无法生成- (int)funcToSwizzle:(int)a andB:(int)b { int r = a+b; NSLog(@"funcToSwizzle: %d", r); return r; } - (void)doSimpleSwizzling { NSLog(@"r1 = %d", [self funcToSwizzle:10 andB:20]); Class curClass = NSClassFromString(@"HPTracer"); unsigned int methodCount = 0; Method *methods = class_copyMethodList( curClass, &methodCount); for (int i=0; i<methodCount; ++i) { SEL originalSelector = method_getName(methods[i]); if ( strcmp("funcToSwizzle:andB:", sel_getName(originalSelector)) == 0 ) { Method m1 = class_getInstanceMethod(curClass, originalSelector); id block3 = ^(id self, int a, int b) { NSLog(@"My block: %d", a*b); // get current implementation of "funcToSwizzle". // copy it. store that "IMP"/"void *" etc return [self funcToSwizzle:a andB:b]; }; IMP imp3 = imp_implementationWithBlock(block3); method_setImplementation(m1, imp3); } } NSLog(@"r2 = %d", [self funcToSwizzle:10 andB:20]); } 或某些方法。有block3但没有NSSelectorFromString

UPD
我看了看DTrace util,它看起来非常强大,但是不符合我的需求。 它要求在Mac OS上禁用SIP,在iOS上是不可能的,在越狱的设备上是不可能的。

我从方法拦截中需要的是为调试和生产构建模式创建一个稳定的自定义“框架”。

0 个答案:

没有答案