views:

123

answers:

1

I want to intercept messages sent to a proxy object by just printing the selector and arguments. Even if the proxy does not implement them and does not have a target object. Please help. I have looked at several options and Apple docs but they assume that you already know the target object. I want to do this cleanly without memory issues.

 @implementation MyProxy

    -(void)forwardInvocation:(NSInvocation*)anInvocation
        {

        // at this point I would

         //like to fetch the arguments and put on an array 
         NSMutableArray *myArgs = .....;
         NSLog(@"Invoking selector %@", theSelector);
         NSLog (myArgs); // this should print me the list of arguments to the method
        }
@end
         // e.g 
            MyProxy *proxy = [[MyProxy alloc] init];
            [proxy SendMeAnyThing: @"hello"]; // this should print me arguments 
        or [proxy add: 12 to: 89 sub: 89]; // should print the arguments

Thanks thanks

+1  A: 

The arguments are of just about any C type, including Objective-C types, that may be passed to the method. Thus, they can't be represented in an array.

Note that invoking a method that is not declared anywhere doesn't make any sense. Quite specifically, the compiler has no idea how to encode the arguments at the call site to make a valid C function call (a method call is really just a C function call to objc_msgSend() or a variant). So, to answer your "any method, even if it doesn't exist" question; no, you can't do that.

You can, however, effectively eliminate all compiler warnings. If you eliminate all compiler warnings -- all "method foo:bar: has can't be found" type warnings -- then that means the compiler does have enough information and you can do whatever the heck you want with a proxy.

Furthermore (as I read more into your question), there is no need to implement any method on the proxy. A proxy can quite happily forward-into-NSInvocation any method call. Written correctly, you can have a proxy stand in for any object without issue.

What you need to do is enumerate the arguments using the API of NSInvocation, sussing out the types and then decoding each argument accordingly and printing appropriately.

You can grab the number of arguments by invoking numberOfArguments on the method signature of the NSInvocation instance (the signature can be had via the methodSignature method).

Then, loop through the arguments and call getArgumentTypeAtIndex: on the method signature to get the type. You would then most likely write a switch() statement on the type encoding to then call getArgument:atIndex: and decode appropriately based on type.

Note that argument 0 is self and argument 1 is _cmd; the SEL of the method that was invoked.

bbum