It’s probably a naive question, But I am feeling kinda lost. I read iOS developer guide about protocols at Apple Documentation, But didn’t quite make sense. Let me explain my dilemma in a shortest possible way.
Lets say I have protocol as below,
@protocol MyProtocol<NSObject>
- (void)someMessage;
@end
And than in my code I am declaring a variable like this,
id<MyProtocol> someVar;
So far so good, But someVar is an id type so where we will implement -(void) someMessage;?
NOTE: I have knowledge such as, Implementation of defined
functions of interface should be inside a Class which implements that
interface. This understanding is from Java so, and in Java it is very
apparent to know which object is from which class and what interface
that class implements. But above Objective C way just confused me :(.
When you write:
you’re simply stating that “someVar” will be an object of any class, but this class will respect the protocol MyProtocol.
So there will be some point in your code that will instantiate someVar. At this point someVar will be associated to a class. This class must satisfy the MyObject protocol.
Note that the compiler will do its best to warn you in case of issues, e.g. if you cast this object to some class that doesn’t respect the protocol, e.g. suppose your protocol defines a method called “protocolMethod” then:
will generate a compiler warning (“NSArray may not respond to protocolMethod”).
Of course you will never be protected from runtime errors: so if at runtime you create someVar to be of a class that doesn’t satisfy the protocol, then any calls to the protocol methods will raise an exception.