我对iPhone中的@protocol ---- @ end感到困惑,究竟是什么意思。我们为什么使用这个。它是一个功能,提供额外的方法,以一个类..?我不确定。iPhone SDK中的协议
请帮帮我。
感谢,
世斌
我对iPhone中的@protocol ---- @ end感到困惑,究竟是什么意思。我们为什么使用这个。它是一个功能,提供额外的方法,以一个类..?我不确定。iPhone SDK中的协议
请帮帮我。
感谢,
世斌
协议用于声明所使用由许多对象或类,其是要的官能度。
考虑一个例子,您正在开发一个鸟类数据库。所以你会把这只鸟作为基础班,你会继承这只鸟来创造你自己的鸟。所以在鸟类中,你将不会有任何定义,但是所有鸟类必须继承的一些行为。像鸟可以飞,有这样的翅膀。那么你将会怎样声明所有这些行为并在你的派生类中实现它们。因为可能会有飞行高度和长距离的鸟类,有些会飞行很短的距离。
为了达到这个目的,使用@protocol。使用@protocol声明一些行为。在你的其他类中使用这些行为来实现行为。
这样可以避免一次又一次地声明同一个方法的开销,并确保您在类中实现该行为。
这是一个不错的职位..并非常明确的解释 – 2012-09-18 10:19:30
@protocol等同于Java的接口。
@protocol Printable // Printable interface
- (void) print;
@end
@interface MyClass: NSObject <Printable> { ... }
// MyClass extends NSObject implements Printable
@protocol可以用来定义一个委托。
例如:
@protocol SomeDelegate
- (void)delegateActionCompleted;
@end
@interface MyClass: NSObject {
id<SomeDelegate> _delegate;
}
@end
然后执行(.M)文件:
@implementation MyClass
- (void)performAction {
// do the actual work
if (self._delegate && [self._delegate respondsToSelector:@selector(delegateActionCompleted)]) {
[self._delegate delegateACtionCompleted];
}
}
@end
应该更好地使用像
if (self.delegate && [self.delegate conformsToProtocol:@protocol(YourProtocolName)]) {
...
}
检查委托是否真正符合规定的协议。
另请参阅此问题:http://stackoverflow.com/questions/1913935/what-are-the-arrow-brackets-in-an-obj-c-class-interface-for – 2010-03-03 02:46:20