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

查看:154
本文介绍了将方法的所有参数传递给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 struct,然后是每个参数类型及其大小。然后,您可以从 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天全站免登陆