将方法的所有参数传递到 NSLog [英] Pass all arguments of a method into NSLog

查看:21
本文介绍了将方法的所有参数传递到 NSLog的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 NSLog() 将一些内容打印到控制台.有没有办法将当前方法的所有参数传递给 NSLog() 或任何其他函数或方法,而无需明确查看它们中的每一个?

I print out something to the console using NSLog(). Is there a way to pass all the current method's arguments to NSLog(), or any other function or method, without looking at each of them explicitly?

例如,当我将 LOGME 放在我的代码中时,我已经有一个宏可以将有用的信息打印到控制台.该宏将创建对单例类的日志记录方法的调用,并传递一些有用的东西,例如 _cmd 和其他东西.

For example, I already have a macro that prints useful information to the console when I just put LOGME in my code. The macro will create a call to a singleton class's logging-method and pass several useful things like _cmd and other stuff.

我还想捕获该方法的所有参数并将它们传递给自动打印出来.这可能吗?

I would also like to catch all the arguments of that method and pass them on for printing them out automatically. Is that possible?

推荐答案

使用 gdb.您可以设置一个断点,记录方法的参数并继续.

Use gdb. You can set a break point that logs the arguments to the method and continues.

如果你坚持用困难的方式来做......这当然不简单,但是你可以在给定的体系结构/ABI上使用堆栈结构,并利用Objective-C运行时来计算出有多少参数和要寻找什么尺寸.从今往后,我处于未知领域;我从来没有这样做过,也不会打扰.所以YMMV...

If you insist on doing it the hard way... It's certainly not simple, but you could use the stack structure on a given architecture/ABI and make use of the Objective-C runtime to figure out how many arguments and of what size to look for. From here on out, I'm in unchartered territory; I've never done this nor would I ever bother. So YMMV...

在您的方法中,您可以获得 Method 结构,然后是参数数量,然后是每个参数类型及其大小.然后,您可以从 self 参数(即 &self)的地址开始遍历堆栈,假设您知道自己在做什么...

Within your method, you can get the Method struct, then the number of arguments, then each argument type and the its size. You could then walk the stack from the address of the self parameter (i.e. &self), assuming you knew what you were doing...

Method method = class_getInstanceMethod([self class], _cmd);
unsigned nargs = method_getNumberOfArguments(method);
void *start = &self;
for(unsigned i = 0; i<nargs; i++) {
  char *argtype = method_copyArgumentType(method, i);
  //find arg size from argtype
  // walk stack given arg zie
  free(argtype);
}

在此过程中,您必须从 argtype 字符串进行转换(使用 Objective-C 类型编码) 到堆栈上每个参数的大小.

Along the way you'd have to convert from the argtype string (using the Objective-C type encodings) to the size of each argument on the stack.

当然,您必须为每种类型派生格式字符串,并使用包含参数的适当可变参数数组调用 NSLogv,从它们在堆栈上的位置复制.可能比它的价值更多的工作.使用调试器.

Of course then you'd have to derive the format string for each type, and call NSLogv with an appropriate variable argument array containing the arguments, copied from their location on the stack. Probably a lot more work than its worth. Use the debugger.

这篇关于将方法的所有参数传递到 NSLog的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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