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

ios, message-forwarding, nsinvocation, selector

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:

- Create a class called `Helper`.

- Add a reference to the class from where you will call the methods, in this format: `id <HelperDelegate> myClassReference;`

- 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];`.

- 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.

Problem

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

Original source