Mac OS X: Method Swizzling in Cocoa

It took me about 45 minutes, but I finally think I have this figured out:

Method Swizzling in Cocoa

Basically, it’s the missing piece you need to effectively “hijack” an existing function in an existing piece of Mac OS X software.

To do this, you follow a few key steps:

  1. You identify a method of an existing class in an existing piece of software that you want to hijack, let’s call it “foo”
  2. You then write your own implementation of that method in that class, let’s call it “myFoo”
  3. You do what ever you want in myFoo, but then you include a call to myFoo. It looks like infinite recursion, but it’s not.
  4. You do the MethodSwizzle trick, which basically tells the Objective-C runtime to replace all calls to “foo” with “myFoo”, and vice-versa.

End result, every existing call to “foo” now calls “myFoo”, and “myFoo” is no longer infinitely recursive because it’s call to “myFoo” now calls “foo”.

It turns out this type of trickery is essential if you want to write a plug-in for an existing application, like Apple Mail, where there is no pre-defined API, and you want to take over pre-existing actions and add some functionality to them.

My work on an Apple Mail plug-in is painfully slow, but I’m at least a little further along now.