You can "type" the
id type to create a type that the compiler will understand implements your protocol, like this:
Code:
@protocol TestProtocol
- (void)method1;
@end
...
id<TestProtocol> anInstanceThatImplementsTestProtocol = ...;
You can use this same technique to type method parameters (the compiler will enforce this with type checking):
Code:
- (void) myMethod:(id<TestProtocol>)param
{
// variables passed as 'param' must implement TestProtocol
}
In general, you can take any
id type object, and ask if it implements a protocol:
Code:
id someUnTypedObject = ...;
if ( [someUnTypedObject conformsToProtocol:@protocol(TestProtocol)] )
{
// yes it does, can call protocol methods on it
[someUnTypedObject someProtocolMethod];
}
Finally, since a protocol can have @optional methods, you can check if an instance implements an optional method:
Code:
id someUnTypedObject = ...;
if ( [someUnTypedObject conformsToProtocol:@protocol(TestProtocol)] )
{
// it conforms to the protocol
if ( [someUnTypedObject respondsToSelector:@selector(someOptionalMethod)] )
{
// safe to send 'someOptionalMethod'
[someUnTypedObject someOptionalMethod];
}
}