An object of type ID in Objective-c can be converted to any kind of object, somewhat similar to the effect of a void* pointer type. The following is a brief description of the ID type.
ID Marker: Common Object type. The ID type is a unique data type that can be converted to any data type, that is, a variable of type ID can hold an object of any data type. What is this for? Or from the OC's internal implementation mechanism to analyze it!
In internal processing, the ID type is defined as a pointer to an object, which can be seen from the definition of the ID. The ID in objc.h is defined as:
typedef struct OBJC_OBJECT {
Class Isa;
} *id;
The class is a typedef struct OBJC_CLASS *class, which is a pointer alias for struct Objc_class, and objc_class is defined in runtime.h as
struct Objc_class {
Class Isa;
#if!__objc2__
Class Super_class objc2_unavailable;
const char *name objc2_unavailable;
Long version objc2_unavailable;
Long info objc2_unavailable;
Long Instance_size objc2_unavailable;
struct Objc_ivar_list *ivars objc2_unavailable;
struct Objc_method_list **methodlists objc2_unavailable;
struct Objc_cache *cache objc2_unavailable;
struct Objc_protocol_list *protocols objc2_unavailable;
#endif
} objc2_unavailable;
As seen from the code above, the ID is a pointer to Objc_object. So why does it point to NSObject objects? Or look at the definition of NSObject!
@interface NSObject <NSObject> {
Class Isa;
}
You can see that NSObject has only one class object, Isa, and Objc_object is only a class object Isa, which can be regarded as equivalent (don't know right?). ). So the ID is a more flexible object pointer, and it is a pointer to any object that inherits the class of object (or NSObject). In the Cocoa development environment, NSObject is the root class for all classes. So the ID can point to any one of the cocoa's legitimate objects.
As you can see from the above code analysis, the ID is actually a pointer to an instance variable of the Nsobjec object, where ID and void* are not exactly the same.
PS:relationship between ID and IMP designator:
ID: is a data type;
IMP: Pointer to the method that returns the ID type value, and the method pointed to with the Self and selector object as the first argument. It is a type C and can be thought of as a function pointer. Its English explanation:IMP is a C type referring to the implementation of a method, also known as an implementation pointer. It's a pointer to a function returning ID, and with self and a method selector (available inside method definitions as the Variable _cmd) as the first arguments.
It is used in the following ways: ID (*IMP) (ID, SEL, ...); (Sel is a type of selector selector, the selector is a pointer to the method)
For the NSObject object, you can get the imp for a given method in this way:
IMP imp=[obj methodforselector: @selector (message)];
For arbitrary object objects,
IMP imp=[obj methodfor: @selector (message)];
OBJECTIVE-C ID Type Implementation principle