代表宣言进退两难

His*_*erg 1 cocoa cocoa-touch objective-c cocoa-design-patterns ios

我很困惑 - 我无法理解代表的目的是什么?

默认情况下创建的Application Delegate是可以理解的,但在某些情况下我看到过类似的内容:

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

//...

@end
Run Code Online (Sandbox Code Playgroud)

有什么<UIScrollViewDelegate>用?

它是如何工作的以及为什么使用它?

Jac*_*kin 12

<UIScrollViewDelegate>是说,类符合UIScrollViewDelegate 协议.

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

如果您愿意,可以将您的班级符合多种协议:

@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>
Run Code Online (Sandbox Code Playgroud)

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

这是一个例子:

Printable.h

@protocol Printable

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

@end
Run Code Online (Sandbox Code Playgroud)

Document.h

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

Document.m

@implementation Document

   //probably tons of code here..

#pragma mark Printable methods

   - (void) print: (Printer *) printer {
       //do awesome print job stuff here...
   }

@end
Run Code Online (Sandbox Code Playgroud)

然后,您可以拥有符合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
Run Code Online (Sandbox Code Playgroud)

  • 为了进一步澄清Jacob的响应......你将使用委托的原因是分配一个类来处理UIScrollView对象依赖的特定任务来正确地完成它的工作.在外行人看来,你可以把它想象成一个私人助理.老板太忙了,无法关心如何订购午餐,所以他有一位代表(他的秘书或其他人),他要求他在一次重要的会议上为他的团队订购午餐.他只是简单地说"嘿Judy,我们需要5个人共进午餐,这就是他们想要的",然后Judy接收了这些信息并做了一些必要的事情来获得午餐. (4认同)