Objective-C Language Optional and required methods


Example

By default, all the methods declared in a protocol are required. This means that any class that conforms to this protocol must implement those methods.

It is also possible to declare optional methods. These method can be implemented only if needed.

You mark optional methods with the @optional directive.

@protocol NewProtocol
- (void)protocolMethod:(id)argument;
@optional
- (id)anotherMethod;
@end

In this case, only anotherMethod is marked as optional; the methods without the @optional directive are assumed to be required.

The @optional directive applies to methods that follow, until the end of the protocol definition or, until another directive is found.

@protocol NewProtocol
- (void)protocolMethod:(id)argument;
@optional
- (id)anotherMethod;
- (void)andAnotherMethod:(id)argument;
@required
- (void)lastProtocolMethod;
@end

This last example defines a protocol with two optional methods and two required methods.