<UIScrollViewDelegate>
是说,类符合的UIScrollViewDelegate
协议。
这实际上意味着该类必须实现UIScrollViewDelegate
协议中定义的所有必需方法。就那么简单。
,如果你喜欢,你可以符合你的类多种协议:
@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>
符合一类的协议的目的是a)宣布类型作为协议的符合性,所以你现在可以将这种类型分类在id <SomeProtocol>
之下,这对于这个类的对象可能属于的委托对象来说更好,以及b)它告诉编译器不要警告你已经实现的方法没有在头文件中声明,因为你的类符合协议。
下面是一个例子:
Printable.h
@protocol Printable
- (void) print:(Printer *) printer;
@end
Document.h
#import "Printable.h"
@interface Document : NSObject <Printable> {
//ivars omitted for brevity, there are sure to be many of these :)
}
@end
Document.m
@implementation Document
//probably tons of code here..
#pragma mark Printable methods
- (void) print: (Printer *) printer {
//do awesome print job stuff here...
}
@end
你可以然后有符合Printable
协议,然后可以在,比如说,一个PrintJob
对象被用作一个实例变量的多个对象:
@interface PrintJob : NSObject {
id <Printable> target;
Printer *printer;
}
@property (nonatomic, retain) id <Printable> target;
- (id) initWithPrinter:(Printer *) print;
- (void) start;
@end
@implementation PrintJob
@synthesize target;
- (id) initWithPrinter:(Printer *) print andTarget:(id<Printable>) targ {
if((self = [super init])) {
printer = print;
self.target = targ;
}
return self;
}
- (void) start {
[target print:printer]; //invoke print on the target, which we know conforms to Printable
}
- (void) dealloc {
[target release];
[super dealloc];
}
@end
为了进一步澄清雅各布的回应...你使用委托的原因是要分配一个类来处理UIScrollView对象依赖的特定任务来正确地工作。用外行人的话说,你可以把它看作是一个私人助理。一位老板太忙了,无法关心午餐的订购方式,因此他有一位代表(他的秘书或其他),他要求他在一次重要会议上为他的团队订购午餐。他只是说:“嗨朱迪,我们需要5人的午餐,这是他们想要的东西”,朱迪然后拿着这些信息,做任何需要做的事情来获得午餐。 – 2010-12-06 06:39:45