In Objective-C, is id exactly the same as void * in C? (a generic pointer type).
If so, when we use
id obj = [[Fraction alloc] init];
[obj methodName];
obj = [[ComplexNumber alloc] init];
[obj anotherMethodName];
When the method is called, by what way does the program know what class obj is?
idis not the same as avoid *.idis a pointer to an Objective C object of unknown type; like theobjectdatatype of C# or Java. Avoid*can point at anything; a non-nilidis expected to point at a data structure that’s common to all ObjC objects and contains a pointer to their respective class data.The ObjC runtime – the implementation of
alloc/init/etc. – makes sure all the valid objects have the right class pointer in them.IIRC, in Apple’s implementation the pointer-sized variable that
idpoints at is, in fact, the pointer to the class.In the class’ data block, there’s a list of methods that maps method signature to the function pointer to the method implementation. From there, it’s a fairly simple lookup that happens in run time when you send a message to (i. e. call a method in) an object. Also a pointer to the base class so that the method lookup may continue up the inheritance tree.
That, by the way, is why derefencing a void pointer is a compiler error while sending messages to an
idis legal, if statically unsafe.