Protocols in iPhone SDK
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 a开发者_如何学JAVAdditional methods to a class..? i am not sure.
Please help me.
Thanks,
Shibin
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.
@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
It should be better to use something like
if (self.delegate && [self.delegate conformsToProtocol:@protocol(YourProtocolName)]) {
...
}
to check whether the delegate is actually conforming to a specified protocol.
精彩评论