Formal and Informal protocols are the two varieties of
An informal protocol is a category on NSObject, which implicitly makes almost all objects adopters of the protocol. (A category is a language feature that enables you to add methods to a class without subclassing it.) Implementation of the methods in an informal protocol is optional. Before invoking a method, the calling object checks to see whether the target object implements it. Until optional protocol methods were introduced in Objective-C 2.0, informal protocols were essential to the way Foundation and AppKit classes implemented delegation.
informal protocol by grouping the methods in a category declaration:
@interface NSObject ( MyXMLSupport )
- initFromXMLRepresentation:(NSXMLElement *)XMLElement;
- (NSXMLElement *)XMLRepresentation;
protocol bends the rules of category declarations to list a group of methods
but not associate them with any particular class or implementation.
Being informal, protocols declared in categories don’t receive much language support. There’s no type checking at compile time nor a check at runtime to see whether an object conforms to the protocol. To get these benefits, you must use a formal protocol. An informal protocol may be useful when all the methods are optional, such as for a delegate, but (on Mac OS X v10.5 and later) it is typically better to use a formal protocol with optional methods.
protocol declares a list of methods that client classes are expected to
implement. Formal protocols have their own declaration, adoption, and
type-checking syntax. You can designate methods whose implementation is
required or optional with the @required and @optional keywords. Subclasses
inherit formal protocols adopted by their ancestors. A formal protocol can also
adopt other protocols.
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.
You declare formal protocols with the @protocol directive:
Unlike class names, protocol names don’t have global visibility. They live in their own namespace.