Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

How are protocols internally implemented?

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.

Upvotes: 3

Views: 460

Answers (2)

Jacob Relkin
Jacob Relkin

Reputation: 163318

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 Protocol struct.

These structs allow access into what a Protocol object contains and its property names should infer what their underlying purpose is.

Some of the members that a Protocol contain are as follows:

  1. A list of objc_method_description structs.
  2. A list of objc_property_t structs.

And of course a method called protocol_getName which 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 @protocol declarations into C structs at compile-time, and the Objective-C methods such as conformsToProtocol: simply perform comparisons on the members of the passed-in struct as generated by the @protocol language construct.

Therefore, you can do something like this:

@protocol BlahProtocol <NSObject>

-(void)blahMethod;
@property (nonatomic, strong) id blahProperty;

@end

//...
Protocol *blah = objc_getProtocol("BlahProtocol");
struct objc_method_description blahMethodDescription = protocol_getMethodDescription(blah, @selector(blahMethod), NO, YES);

NSLog(@"%s %s", blahMethodDescription.name, blahMethodDescription.types);

objc_property_t blahProperty = protocol_getProperty(blah, "blahProperty", NO, YES);

NSLog(@"%s", property_getAttributes(blahProperty));

Upvotes: 3

Anya Shenanigans
Anya Shenanigans

Reputation: 94859

protocols work by specifying that a certain method is invoked. You ask if the object 'respondsToSelector', to check if it implements a specific method, then you invoke it by invoking the method.

Upvotes: 0

Related Questions