What's the difference between formal and informal protocols in Objective-C?

后端 未结 3 1981
南方客
南方客 2021-01-31 03:04

What\'s the difference between formal and informal protocols in Objective-C?

相关标签:
3条回答
  • 2021-01-31 03:08

    From Official Documentation

    Formal and Informal Protocols

    There are two varieties of protocol, formal and informal:

    • 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.

    • A formal 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 an extension to the Objective-C language.

    0 讨论(0)
  • 2021-01-31 03:26

    The Objective-C language provides a way to formally declare a list of methods (including declared properties) 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.

    0 讨论(0)
  • 2021-01-31 03:31

    Informal Protocol : Category (Implementations are Optional)

    Formal Protocol : Extension (Implementations are Optional and required)

    0 讨论(0)
提交回复
热议问题