I am trying to modify behaviour of a program (i dont have it's source) using SIMBL. I used class dump and found out that I need to overide an instance method
This method is in the class called controller. All I need to do is get the argument arg1 and thats it. Maybe NSLog it or post a notification... I read about method swizzling in objective-c but how can I use it?. I would need to refer to the class MessageController whose course i don't have.
Thanks!
The library jrswizzle handles it. Doing it yourself is not recommended, because there are a lot of details to get right. (See the table documenting the failures of previous implementations in the jrswizzle readme.)
Say you have class like this:
You can use it like this:
Output:
I'm guessing you need to call the original implementation after doing your NSLog; if not, you may be able to just use a category on the class to override the method.
To swizzle the method, first you need a replacement method. I usually put something like this in a category on the target class:
This looks like it will recursively call itself, but it won't because we're going to swap things around so calling
ReceiveMessage:
calls this method while callingreplacementReceiveMessage:
calls the old version.The second step is to use the runtime functions to actually perform the swap. The advantage of using a category is that you can use
load
in the category to do the work:There are two cases that need to be handled:
class_addMethod
to add an implementation ofReceiveMessage:
to the target class, which we do using our replacement implementation. Then we can useclass_replaceMethod
to replacereplacementReceiveMessage:
with the superclass's implementation, so our new version will be able to correctly call the old.class_addMethod
will fail but then we can usemethod_exchangeImplementations
to just swap the new and old versions.