I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate
protocol for example.
How can I define a protocol of my own, and set a few of the methods as optional?
I noticed methods marked optional in several protocols defined in the iPhone SDK, such as the UIActionSheetDelegate
protocol for example.
How can I define a protocol of my own, and set a few of the methods as optional?
Use the @optional
keyword before your method declaration to make it optional. Simple as that!
// myProtocol.h
@protocol myProtocol
- (void)myMandatoryMethod:(id)someArgument;
@optional
- (void)myOptionalMethod:(id)someArgument;
@end
// myClass.m
@interface myClass : someSuperClass <myProtocol>
//...
@end
From the Apple page on "Formal Protocols":
Optional Protocol Methods 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
Keep in mind that the @optional keyword is new in Objective-C 2.0. Prior to Leopard, you would have typically declared an informal protocol as a category of NSObject.