iosselectornsinvocationmessage-forwarding

Is there a way to observe every message calls invoked on an object (iOS)?


I just want to get a selector name, and the arguments, sender, or an NSInvocation instance every time when I send a message to an object. Possible? Something like forwardInvocation:, but in evey case (every method call).


Solution

  • There is way to get the selector's name and the target by using the hidden parameters in objective-c messaging. From Apple's documentation:

    When objc_msgSend finds the procedure that implements a method, it calls the procedure and passes it all the arguments in the message. It also passes the procedure two hidden arguments:

    The receiving object The selector for the method

    So in a method you can get the following:

       id  target = getTheReceiver();
       SEL method = getTheMethod();
    

    If it's still not enough for your needs, you can do the following:

    1. Create a class called Helper.
    2. Add a reference to the class from where you will call the methods, in this format: id <HelperDelegate> myClassReference;
    3. When you need to make a [self method] instead create an instance of this Helper class and call the method on it like [helper method]; and add this [helper setMyClassReference:self];.
    4. The app should crash, but then, just add the forwardInvocation: on the Helper class. From there, you will be able to get the NSInvocation object. Do what you need to do, and then: [anInvocation invokeWithTarget:myClassReference]; so you can pass the message to the original caller.

    P.S: Even if this doesn't answer your question, +1 for the question.. Really got me thinking about this.