有没有一种方法可以记录给定类的每个方法的每次调用? [英] Is there a way to log every call to every method for a given class?

查看:141
本文介绍了有没有一种方法可以记录给定类的每个方法的每次调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a way to log every call to every method of a given UIView for debug purposes.

推荐答案

这是我为此编写的代码

使用以下步骤:


  1. 通过从 NSProxy

  2. Swizzle allocWithZone:在目标类上,并将返回的对象与代理类包装在一起

  3. forwardInvocation中记录消息:在代理类中

  1. Create a proxy class by subclassing from NSProxy
  2. Swizzle allocWithZone: on the target class and wrap the returned object with the proxy class
  3. Log message in forwardInvocation: at the proxy class







#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

这篇关于有没有一种方法可以记录给定类的每个方法的每次调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆