Type Method 型メソッド

conformsToProtocol:

Returns a Boolean value that indicates whether the target conforms to a given protocol.

Declaration 宣言

+ (BOOL)conformsToProtocol:(Protocol *)protocol;

Parameters パラメータ

protocol

A protocol. あるプロトコル。

Return Value 戻り値

YES if the target conforms to protocol, otherwise NO.

Discussion 解説

A class “conforms to” a protocol if it adopts the protocol or inherits from another class that adopts it. Classes adopt protocols by listing them within angle brackets after the interface declaration. For example, here MyClass adopts the (fictitious) AffiliationRequests and Normalization protocols:


@interface MyClass : NSObject <AffiliationRequests, Normalization>

A class also conforms to any protocols included in the protocols it adopts or inherits. Protocols incorporate other protocols in the same way classes adopt them. プロトコルは、クラスがそれらを採用するのと同じ方法で他のプロトコルを取り入れます。 For example, here the AffiliationRequests protocol incorporates the Joining protocol:


@protocol AffiliationRequests <Joining>

If a class adopts a protocol that incorporates another protocol, it must also implement all the methods in the incorporated protocol or inherit those methods from a class that adopts it. あるクラスが別のプロトコルを取り入れるプロトコルを採用するならば、それは、取り入れられたプロトコル中の全てのメソッドを実装するか、それを採用するクラスからそれらのメソッドを継承しなければなりません。

This method determines conformance solely on the basis of the formal declarations in header files, as illustrated above. It doesn’t check to see whether the methods declared in the protocol are actually implemented—that’s the programmer’s responsibility. このメソッドは、ただ単にヘッダファイル中の形の上での宣言に基づいて準拠を、上で説明されるように、判定します。それは、プロトコルで宣言されるメソッドが実際に実装されるかどうか確認しません—それはプログラマーの責任です。

To specify the protocol required as this method’s argument, use the @protocol() directive:


BOOL canJoin = [MyClass conformsToProtocol:@protocol(Joining)];

Performance Considerations

Calling this method in performance sensitive code can cause unwanted performance problems. conformsToProtocol: requires taking the Objective-C runtime lock and traversing the target’s class hierarchy to check for protocol conformance, which can take significant time.

Consider the following alternatives in your code:

  • Use respondsToSelector: to check for methods in the protocol instead, especially if you only need to check some of the protocol’s methods.

  • If you do need to use conformsToProtocol:, cache the result whenever possible, rather than calling this method repeatedly.