Formal protocols in Objective-C are a powerful feature that define a set of methods that a class can choose to implement. They serve as a contract between classes, ensuring that certain methods are available for use.
Formal protocols declare a list of methods that any conforming class must implement. They're similar to interfaces in other programming languages and play a crucial role in Objective-C Polymorphism.
To define a formal protocol in Objective-C, use the @protocol
keyword followed by the protocol name and a list of method declarations:
@protocol MyProtocol
- (void)requiredMethod;
@optional
- (void)optionalMethod;
@end
In this example, requiredMethod
must be implemented by any class adopting the protocol, while optionalMethod
is optional.
To adopt a protocol, list it in angle brackets after the superclass name in the class declaration:
@interface MyClass : NSObject <MyProtocol>
@end
@implementation MyClass
- (void)requiredMethod {
// Implementation here
}
@end
Objective-C allows a class to adopt multiple protocols, enabling a form of multiple inheritance for method declarations:
@interface MyClass : NSObject <ProtocolA, ProtocolB>
@end
While not as powerful as Swift protocol extensions, Objective-C allows you to provide default implementations for protocol methods using Objective-C Categories:
@interface NSObject (MyProtocolDefaults) <MyProtocol>
@end
@implementation NSObject (MyProtocolDefaults)
- (void)optionalMethod {
// Default implementation
}
@end
Formal protocols are a cornerstone of Objective-C programming, enabling flexible and modular code design. They're extensively used in iOS and macOS development, particularly in delegate patterns and framework APIs. Understanding and effectively using protocols is crucial for writing clean, maintainable Objective-C code.