1

我很困惑 - 我不明白代表的用途是什么?

默认创建的 Application Delegate 是可以理解的,但在某些情况下我看到过这样的事情:

@interface MyClass : UIViewController <UIScrollViewDelegate> {
    UIScrollView *scrollView;
    UIPageControl *pageControl;
    NSMutableArray *viewControllers;
    BOOL pageControlUsed;
}

//...

@end

<UIScrollViewDelegate>为了什么?

它是如何工作的,为什么要使用它?

4

2 回答 2

12

<UIScrollViewDelegate>是说该类符合UIScrollViewDelegate 协议

这真正意味着该类必须实现UIScrollViewDelegate协议中定义的所有必需方法。就那么简单。

如果您愿意,您可以使您的课程符合多种协议:

@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>

使类符合协议的目的是 a) 将类型声明为协议的符合者,因此您现在可以将此类型分类为id <SomeProtocol>,这对于此类对象可能属于的委托对象更好,并且 b)它告诉编译器不要警告您未在头文件中声明已实现的方法,因为您的类符合协议。

这是一个例子:

可打印的.h

@protocol Printable

 - (void) print:(Printer *) printer;

@end

文档.h

#import "Printable.h"
@interface Document : NSObject <Printable> {
   //ivars omitted for brevity, there are sure to be many of these :)
}
@end

文档.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
于 2010-12-06T06:27:53.857 回答
2

I think you need to understand the Delegate Pattern. It is a core pattern used by iphone/ipad applications and if you don't understand it you will not get far. The link to wikipedia I just used outlines the pattern and gives examples of it's use including Objective C. That would be a good place to get started. Also look at take a look at the Overview tutorial from Apple which is specific to the iPhone and also discusses the Delegate pattern.

于 2010-12-06T06:54:16.150 回答