As far as I know, classes in Objective-C are stored in terms of C structures.
How are protocols implemented?
I’d like to understand this in simple terms.
What does [NSObject conformsToProtocol:] do to check whether a class conforms to the protocol or not?
Is there a table or data structure for a protocol that tells what selectors there are in a protocol?
NOTE: The term “protocol” here is used to refer to a Objective C construct not a network protocol.
If you look at the Objective-C Runtime Reference, you will see that there are several functions which allow you to retrieve & inspect the contents of a so-called
Protocolstruct.These structs allow access into what a
Protocolobject contains and its property names should infer what their underlying purpose is.Some of the members that a
Protocolcontain are as follows:objc_method_descriptionstructs.objc_property_tstructs.And of course a method called
protocol_getNamewhich will give you the name of the protocol itself.I think this should be adequate in inferring for yourself how these protocols are implemented by the Objective-C compiler + runtime.
My idea for how they’re actually implemented is that the compiler turns these so-called
@protocoldeclarations into C structs at compile-time, and the Objective-C methods such asconformsToProtocol:simply perform comparisons on the members of the passed-in struct as generated by the@protocollanguage construct.Therefore, you can do something like this: