objective C log method call [duplicate]

那年仲夏 提交于 2020-01-01 14:57:07

问题


Possible Duplicate:
How to pass all arguments of a method into NSLog?

I can setup a macro printCommand to log the receiver and selector of a method call as follows:

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

Question -- can the above be extended to log all arguments that were passed with the method call, however few or many, and whatever types, they may be?


回答1:


Yes you can do this, but it's quite difficult.

The trick is to realize that a method is really just a function, and that you can create a va_list from the arguments, even if the method/function wasn't declared to take ... in the signature.

The pseudo code would be something roughly like this:

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);

Fortunately, other people have wanted this sort of thing before and have come up with pretty much this same mechanism for doing it. Here's an example of something that will NSLog an arbitrary expression:

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



来源:https://stackoverflow.com/questions/6554752/objective-c-log-method-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!