gpt4 book ai didi

ios - 有没有办法记录对给定类的每个方法的每次调用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:42 24 4
gpt4 key购买 nike

我正在寻找一种方法来记录对给定 UIView 的每个方法的每次调用以进行调试。

最佳答案

This is the code I wrote to do it

使用以下步骤:

  1. 通过继承 NSProxy 创建一个代理类
  2. 在目标类上 Swizzle allocWithZone: 并用代理类包装返回的对象
  3. 在代理类的 forwardInvocation: 中记录消息

#import <objc/runtime.h>

@interface XLCProxy : NSProxy

+ (id)proxyWithObject:(id)obj;

@end

@implementation XLCProxy
{
id _obj;
}

+ (void)load
{
{
Class cls = NSClassFromString(@"IDESourceCodeDocument");
id metacls = object_getClass(cls);
IMP imp = class_getMethodImplementation(metacls, @selector(allocWithZone:));
IMP newimp = imp_implementationWithBlock(^id(id me, SEL cmd, NSZone *zone) {
id obj = ((id (*)(id,SEL,NSZone*))(imp))(me, cmd, zone);
return [XLCProxy proxyWithObject:obj];
});
BOOL success = class_addMethod(metacls, @selector(allocWithZone:), newimp, [[NSString stringWithFormat:@"@@:%s", @encode(NSZone*)] UTF8String]);
if (!success) {
NSLog(@"Add method failed");
}
}
}

+ (id)proxyWithObject:(id)obj
{
XLCProxy *proxy = [self alloc];
proxy->_obj = obj;
return proxy;
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
const char *selname = sel_getName([invocation selector]);

[invocation setTarget:_obj];
[invocation invoke];

if ([@(selname) hasPrefix:@"init"] && [[invocation methodSignature] methodReturnType][0] == '@') {
const void * ret;
[invocation getReturnValue:&ret];
ret = CFBridgingRetain([XLCProxy proxyWithObject:_obj]);
[invocation setReturnValue:&ret];
}


NSLog(@"%@ %s", [_obj class], selname);
// if ([[invocation methodSignature] methodReturnType][0] == '@') {
// NSObject __unsafe_unretained * obj;
// [invocation getReturnValue:&obj];
// NSLog(@"%@", obj);
// }
}

-(NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
return [_obj methodSignatureForSelector:sel];
}

- (Class)class
{
return [_obj class];
}

@end

关于ios - 有没有办法记录对给定类的每个方法的每次调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26498519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com