Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept method call in Objective-C

Can I intercept a method call in Objective-C? How?

Edit: Mark Powell's answer gave me a partial solution, the -forwardInvocation method. But the documentation states that -forwardInvocation is only called when an object is sent a message for which it has no corresponding method. I'd like a method to be called under all circumstances, even if the receiver does have that selector.

like image 820
luvieere Avatar asked Oct 24 '09 16:10

luvieere


People also ask

What is intercept C#?

Interception. Fody provides basic interceptors to intercept methods, properties and constructors and its feature-set is aimed towards eliminating boilerplate code.


2 Answers

You do it by swizzling the method call. Assuming you want to grab all releases to NSTableView:

static IMP gOriginalRelease = nil;
static void newNSTableViewRelease(id self, SEL releaseSelector, ...) {
   NSLog(@"Release called on an NSTableView");
   gOriginalRelease(self, releaseSelector);
}


  //Then somewhere do this:
  gOriginalRelease = class_replaceMethod([NSTableView class], @selector(release), newNSTableViewRelease, "v@:");

You can get more details in the Objective C runtime documentation.

like image 181
Louis Gerbarg Avatar answered Oct 04 '22 21:10

Louis Gerbarg


Intercepting method calls in Objective-C (asuming it is an Objective-C, not a C call) is done with a technique called method swizzling.

You can find an introduction on how to implement that here. For an example how method swizzling is implemented in a real project check out OCMock (an Isolation Framework for Objective-C).

like image 36
Johannes Rudolph Avatar answered Oct 04 '22 22:10

Johannes Rudolph