The Objective-C language provides a way to formally declare a list of methods as a protocol. Formal protocols are supported by the language and the runtime system. For example, the compiler can check for types based on protocols, and objects can introspect at runtime to report whether or not they conform to a protocol.
Declaring a Protocol
Optional Protocol Methods
You declare formal protocols with the @protocol directive:
@protocol ProtocolName |
method declarations |
@end |
For example, you could declare the XML representation protocol like this:
@protocol MyXMLSupport |
- (NSXMLElement *)XMLRepresentation; |
- initFromXMLRepresentation:(NSXMLElement *)XMLElement; |
@end |
Unlike class names, protocol names don’t have global visibility. They live in their own namespace.
Protocol methods can be marked as optional using the @optional keyword. Corresponding to the @optional modal keyword, there is a @required keyword to formally denote the semantics of the default behavior. You can use @optional and @required to partition your protocol into sections as you see fit. If you do not specify any keyword, the default is @required.
@protocol MyProtocol |
- (void)requiredMethod; |
@optional |
- (void)anOptionalMethod; |
- (void)anotherOptionalMethod; |
@required |
- (void)anotherRequiredMethod; |
@end |
Last updated: 2008-02-05