I'm wondering how does a typical (or at least Apple's) implementation of the Objective C dynamic messaging system look. How开发者_运维技巧 are selectors handled at compile and run time, what does NSObject*
really point at, how is the method implementation found in there.
In C++, we have virtual functions; how they are implemented is officially an implementation detail, but in reality a VF table pointer as a first data member is pretty much a given. I'm wondering if there's a similarly ubiquitous way of implementing ObjC's class system.
This can be quite lengthy. ughoavgfhw’s answer is a good start.
I’d recommend reading the following blog posts:
- bbum’s objc_msgSend() Tour Parts 1, 2, 3, 4
- mikeash’s Friday Q&A 2009-03-20: Objective-C Messaging
And if you’re not afraid of delving into source code, objc and clang are available at Apple’s Open Source Web site.
Check out the headers in /usr/include/objc
on your nearest development Mac for some of the low-level object details. (Apple has changed some things in the new runtime, but many of the changes haven't been published. Details on the original implementation can be found in these headers, or by googling "objective c runtime".) Some highlights: An object is simply a structure containing the instance variables. The first element in this structure is called isa
, and is simply a pointer to the class object (or superclass for a class object). The class object contains data specifying the name and location of different methods and variables within the class, and the runtime references these data structures when looking up a method. Once a method has been looked up the first time, it is stored in a table for quick future reference.
Apple's official Objective-C Runtime Reference documents the C library that provides all of Objective-C's dispatches, reflection and other object-oriented tasks. Most of the actual data structures used are opaque — I think all of them are since 10.5 — and there's no reason to suppose a continuous line in implementation back to 1986.
The compiler just converts your Objective-C stuff into calls to the runtime; you can also call it yourself to get things like C function pointers to your methods, which you can then dispatch to without the normal overhead though at the cost of a whole bunch of other mechanisms no longer working.
精彩评论