Hi All,
I am confused about the @protocol----@end in iphone, what actually is it meant for. Why we are using this. Is it a functionality to provide additional methods to a class..? i am not sure.
Please help me.
Thanks,
Shibin
Hi All,
I am confused about the @protocol----@end in iphone, what actually is it meant for. Why we are using this. Is it a functionality to provide additional methods to a class..? i am not sure.
Please help me.
Thanks,
Shibin
@protocol is equivalent to an interface in Java.
@protocol Printable // Printable interface
- (void) print;
@end
@interface MyClass: NSObject <Printable> { ... }
// MyClass extends NSObject implements Printable
@protocol can be used to define a delegate.
For example:
@protocol SomeDelegate
- (void)delegateActionCompleted;
@end
@interface MyClass: NSObject {
id<SomeDelegate> _delegate;
}
@end
And then the implementation (.m) file:
@implementation MyClass
- (void)performAction {
// do the actual work
if (self._delegate && [self._delegate respondsToSelector:@selector(delegateActionCompleted)]) {
[self._delegate delegateACtionCompleted];
}
}
@end
Yes, by using protocols you can indeed extend the functionalities of your class without actually sub-classing the class. The existing class can be added with new methods which does the required tasks.
You cant add new instance variables to the class using protocols though!
Hi Shibin Moideen,
protocol is used to declare a functionality which is going to used by many objects or classes.
Consider an example, You are developing a birds database. So you will be having the bird as a Base class and you will inherit the bird to create your own bird. so in bird class you will not be having any definitions but some behaviors which all birds will have to inherit. Like birds can fly, has wings like that. So what will you d is you will declare all those behaviors and implement them in your derived classes. Because there may be birds which cal fly high and for long distance and some will fly short distances.
For serving this purpose @protocol is used. Using @protocol you declare some behaviors. And use those behaviors in your other classes for implementing the behavior.
This will avoid the overhead of declaring same method again and again and makes sure that you implement the behavior in your class.