My understanding is that objects and classes in Objective-C are just structs.
This isn't really true, particularly since ObjC2, and definitely isn't a good way of thinking about it. The "struct" in question has a single field (isa
) defined. That's it. It's a "struct" in name only.
Note that under ARC objects and structs are treated differently by the compiler. Objects pointers will get special handling (including nil-initialization) that a struct pointer will not. The compiler will also apply ->
differently to an object than it does to a struct. A struct pointer must have a field with the name given after the ->
. objc_object
only has one field (isa
). Since class hierarchies can be defined and redefined at runtime, the compiler cannot evaluate ->
for an object at compile time as it does for a struct.
I make this point because in C++, objects and structs are just slightly different versions of the same thing, and you can easily swap between them. You cannot safely do that in ObjC. They're not nearly as similar.
But when we call a class method, a class, which is of type
struct objc_class *
, I would expect it to cause problem…
This is because classes are objects. Objects are not defined in terms of being of type objc_object
. They're defined in terms of having an isa
field (it used to be a pointer, but now it might be a pointer, or it might not). This is part of the problem of assuming that the typedef is the important thing. It isn't. What matters is whether it acts like an object. Objective-C is a mostly duck-typed language. If it acts like an object, it's an object.
BTW, NSProxy
also lives in this weird almost-an-object world. If you note its definition, it does not inherit from anything, but it does declare an isa
field as its first ivar. That's the critical part of making it act like an object.
Can struct objc_class * and struct objc_object * really be used interchangeably?
No. You can generally pass a class to anything that wants an object (since a class is an object), but you cannot pass an object to things that want a class.