Objective-C Protocols
I came across the following bit of code in a file called TileOverlay.h开发者_开发技巧:
@protocol TileOverlay <MKOverlay>
I'm trying to understand explicitly what this is doing. Several other overlays then import this .h file. Does this file essentially just create a modified version of the MKOverlay class?
If not, can you please clarify what it does?
MKOverlay
is a protocol, and TileOverlay
is a protocol that extends MKOverlay
.
Any class that conforms to the TileOverlay
protocol also conforms to the MKOverlay
protocol.
Refer to Protocols Within Protocols in the documentation for a detailed explanation.
You can think of protocols like interfaces in Java or C#, basically they declare a contract that the implementing classes must follow. The difference is that in Objective C you can make some of the declared methods optional.
It's called protocol inheritance.
MKOverlay
is a protocol, defining a set of methods for objects to implement.
TileOverlay
inherits for MKOverlay
, meaning that an object conforming to TileOverlay
, should implement methods from MKOverlay
and methods from TileOverlay
Here is a link that talks a little bit more about protocol inheritance
A protocol in Objective-C is what you in Java or C# would call an interface. It is a contract that any other class can fulfill, in Obj-C parlance conform to.
This:
@protocol TileOverlay <MKOverlay>
Defines a protocol named TileOverlay
that in itself extends MKOverlay
. That is by conforming to TileOverlay
you must also conform to MKOverlay
.
Protocols in Obj-C, just as interfaces in Jave or C#, is not related to implementation. It does not do anything. It's just a marker at compile time, and at run-time if you want to, to check if some functionally exist.
精彩评论