1

I recently started a project where I require to do swizzling.

After going through many tutorials I got a question, What is the difference between Implementation and function pointer?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
bikram990
  • 1,085
  • 1
  • 14
  • 36

1 Answers1

3

From memory, an IMP is a memory-address just like a function pointer, and can be invoked just like an ordinary C function. However it is guaranteed to use objective-C messaging convention, where:

  • The first argument is the object to operate on (self).
  • The second argument is the _cmd (SELECTOR) to be invoked. I believe this is so to support dynamic features, such as ObjC message forwarding where we could wrap the original implementation in a proxy, say to start a transaction or perform a security check, or, for a Cocoa specific example, add some property observation cruft, by magic, at run-time. While we already have the function signature, I could be helpful, in some cases, to know "how did I get here?" with the message signature.
  • Following arguments, if any, are according to the method contract.
Jasper Blues
  • 28,258
  • 22
  • 102
  • 185
  • I think it's `self` *then* `SEL`. – trojanfoe Dec 30 '15 at 04:59
  • @jasper In all the tutorials first argument is self and the second is _cmd. – bikram990 Dec 30 '15 at 04:59
  • Oops, fixed thanks. Probably someone will give a more detailed answer. – Jasper Blues Dec 30 '15 at 05:00
  • 1
    Not sure there is much more to say about it :) – trojanfoe Dec 30 '15 at 05:00
  • I added a little rant (hopefully correct) about why SEL is there, when we already have a function signature. – Jasper Blues Dec 30 '15 at 05:06
  • @JasperBlues I already came to the above conclusion after reading http://www.cocoawithlove.com/2008/02/imp-of-current-method.html – bikram990 Dec 30 '15 at 05:13
  • 1
    I'm looking if they are almost same. – bikram990 Dec 30 '15 at 05:15
  • 1
    This is correct; an `IMP` _is_ a function pointer, pointing to the contents of an ObjC method. The only thing that might be added here would be its definition as a type: `typedef id (*IMP)(id, SEL, ...)`, in [objc.h in the runtime library](http://www.opensource.apple.com/source/objc4/objc4-680/runtime/objc.h). @bikram990 See also [Apple's ObjC Runtime Reference](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ObjCRuntimeRef/#//apple_ref/doc/uid/TP40001418-CH3g-116261) – jscs Dec 30 '15 at 20:22