I am new to Objective C, I wanted to understand protocol
concept more clearly.
@protocol protocolName
@optional
@required
@end
Can I correlate @optional
part with virtual function and @required
part with pure virtual function of C++?
Is @protocol
is way of Objective-C to create interface and abstract class?
Is @protocol is way of Objective-C to create interface and abstract class?
Exactly.
Can I correlate @optional part with virtual function and @required part with pure virtual function of C++?
Yes you can but there is one difference - if classA does not implement OptionalProtocolMethodB, any attempt to call [classA OptionalProtocolMethodB] will cause a runtime exception. Calling a virtual function in C++ will not.
You should check if the class implements the optional method before calling it. Example:
if ([_delegate respondsToSelector:@selector(didUploadedTotalBytes: totalBytesExpectedToWrite:)]) {
[_delegate didUploadedTotalBytes:_uploadedBytes totalBytesExpectedToWrite:_totalBytes];
}
Forget about abstract classes in Objective-C (there are none). Forget about protocols in connection with class hierarchy.
A protocol describes a set of methods that an object needs to implement to be usable for some purposes. For example, if a protocol has two required methods "color" and "setColor", then any instance of any class implementing these two methods can be used. In addition, the class must claim that it supports the protocol - this avoids a class being used by coincidence. On the other hand, all methods in a protocol could be optional and a class could claim to support the protocol without implementing any of the methods.
There will usually be a description of what happens when optional methods are not implemented. For example, the documentation for an optional method returning BOOL might say "if not implemented, it is assumed that the method returns YES". In other cases the documentation might say under which circumstances an optional method will be called. In any case, the caller must check that an optional method is implemented before calling it using "respondsToSelector". (Of course, the documentation might say for example that if wantsComplexBehaviour returns YES, then doComplexBehaviour1 and doComplexThings2 must be implemented, and not implementing that would be a programmer error punished with an exception when the methods get called).
This is usually all done in a very pragmatic way. Many classes that you use need delegate objects which implement some protocol, so you either add the protocol methods to your implementation and make yourself the delegate, or you create a class for the sole purpose of creating these delegates and implement all the protocol methods in the implementation of that class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With