有没有一种方法可以记录给定类的每个方法的每次调用? [英] Is there a way to log every call to every method for a given class?
本文介绍了有没有一种方法可以记录给定类的每个方法的每次调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种方法来记录对给定UIView的每个方法的每次调用,以进行调试。
I'm looking for a way to log every call to every method of a given UIView for debug purposes.
推荐答案
使用以下步骤:
- 通过从
NSProxy
- Swizzle
allocWithZone:
在目标类上,并将返回的对象与代理类包装在一起 - 在
forwardInvocation中记录消息:
在代理类中
- Create a proxy class by subclassing from
NSProxy
- Swizzle
allocWithZone:
on the target class and wrap the returned object with the proxy class - 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屋!
查看全文