目标C日志方法调用

可能重复:
如何将一个方法的所有参数传入NSLog?

我可以设置一个macrosprintCommand来logging方法调用的接收器和select器,如下所示:

#define printMethodCall NSLog (@"%@ %@", self, NSStringFromSelector(_cmd)); 

问题 – 可以扩展上面的所有参数,通过方法调用传递,但是很less或很多,以及任何types,他们可能是?

是的,你可以做到这一点,但这是相当困难的。

诀窍是认识到一个方法实际上只是一个函数,并且即使方法/函数没有被声明为签名中的... ,也可以从参数创build一个va_list

伪代码大概是这样的:

 va_list args; // start your argument list after the "_cmd" argument va_start(args, _cmd); // get the Method for this (instance) method Method thisMethod = class_getInstanceMethod([self class], _cmd); // get the type encoding string for this method const char *methodType = method_getTypeEncoding(thisMethod); // use the type encoding string to make an NSMethodSignature NSMethodSignature *signature = [NSMethodSignature signatureWithObjCTypes:methodType]; // iterate through all the arguments, skipping 0 (self) and 1 (_cmd) for (NSUInteger i = 2; i < [signature numberOfArguments]; ++i) { // get the type of the argument const char *type = [signature getArgumentTypeAtIndex:i]; // if this argument type is the same as an object, pull out an object if (strcmp(@encode(id), type) == 0) { id nextArg = va_arg(args, id); NSLog(@"object argument: %@", nextArg); // if this argument type is the same as a float, pull out a float } else if (strcmp(@encode(float), type) == 0) { float nextArg = va_arg(args, float); NSLog(@"float argument: %f", nextArg); } ... // repeat as necessary for all the types you care to log } // cleanup va_end(args); 

幸运的是 ,其他人之前也想要这样的事情,并且提出了几乎相同的机制。 下面是NSLog一个任意expression式的例子:

http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/