【问题标题】:objective C log method call [duplicate]目标C日志方法调用[重复]
【发布时间】:2011-09-27 03:20:43
【问题描述】:
【问题讨论】:
标签:
iphone
objective-c
ios
debugging
macros
【解决方案1】:
是的,你可以做到这一点,但这很困难。
诀窍是要意识到一个方法实际上只是一个函数,并且您可以从参数创建一个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 任意表达式的示例:
http://vgable.com/blog/2010/08/19/the-most-useful-objective-c-code-ive-ever-written/