appel de la méthode log C objective

Dupliquer possible:
Comment passer tous les arguments d'une méthode dans NSLog?

Je peux configurer une macro printCommand pour save le récepteur et le sélecteur d'un appel de méthode comme suit:

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

Question – Est-ce que ce qui précède peut être étendu pour consigner tous les arguments qui ont été passés avec l'appel de la méthode, peu ou beaucoup, et quels qu'ils soient, ils peuvent l'être?

Oui, vous pouvez le faire, mais c'est assez difficile.

L'astuce consiste à réaliser qu'une méthode est vraiment juste une fonction, et que vous pouvez créer une va_list partir des arguments, même si la méthode / fonction n'a pas été déclarée pour prendre ... dans la signature.

Le pseudo code serait quelque chose comme ceci:

 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 ssortingng for this method const char *methodType = method_getTypeEncoding(thisMethod); // use the type encoding ssortingng 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); 

Heureusement , d'autres personnes ont voulu ce genre de chose avant et ont trouvé à peu près le même mécanisme pour le faire. Voici un exemple de quelque chose qui va NSLog une expression arbitraire:

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