I want to know how the object-oriented functions of the language are implemented in C.
As defined in <objc/runtime.h> , the id type is a pointer to objc_object , and the type objc_object is a C structure with one isa member that stores Class . Then, where and how are the actual values โโof any object instances stored?
One more thing: the fact that all pointers to objective-C objects can be added to id (which is a pointer to a C structure where there is no function like inheritance) are objective-C classes, qualifiers for the compiler, and all instances same type objc_object ?
added by:
NSObject *obj = [NSObject new]; objc_object *objStruct = (__bridge objc_object *)obj; NSLog(@"obj: %@", NSStringFromClass(objStruct->isa)); NSString *str = [NSString new]; objc_object *strStruct = (__bridge objc_object *)str; NSLog(@"str: %@", NSStringFromClass(strStruct->isa));
This code compiles and outputs:
obj: NSObject, str: __NSCFConstantString
Both obj and str can be translated into objc_object * , which means that both variables are pointers of the same type, no?
allowed
Got it! I did not understand how pointer casting works. obj and str are pointers to different types of structure, but both usually have an element of type isa in front of the memory, so it can be thought of as objc_object . The code below imitates this mechanism:
typedef struct { int isa; } Fake_NSObject; typedef struct { int isa; char *string; } Fake_NSString; Fake_NSObject obj = {1}; Fake_NSObject *objPtr = &obj; NSLog(@"obj: %d", objPtr->isa);
Thanks!
source share