代表声明困境

Posted

技术标签:

【中文标题】代表声明困境【英文标题】:Delegate declaration dilemma 【发布时间】:2010-12-06 06:24:46 【问题描述】:

我很困惑 - 我不明白委托的用途是什么?

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

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


//...

@end

&lt;UIScrollViewDelegate&gt; 有什么用?

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

【问题讨论】:

【参考方案1】:

&lt;UIScrollViewDelegate&gt; 表示该类符合 UIScrollViewDelegate 协议

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

如果你愿意,你可以让你的类符合多种协议:

@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>

使类符合协议的目的是 a) 将类型声明为协议的符合者,因此您现在可以将此类型归类为 id &lt;SomeProtocol&gt;,这对于此类对象可能的委托对象更好属于,并且 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

【讨论】:

为了进一步澄清 Jacob 的回应......您使用委托的原因是分配一个类来处理 UIScrollView 对象依赖的特定任务来正确完成工作。用外行的话,你可以把它想象成一个私人助理。老板忙得无暇顾及午餐是怎么点的,所以他请了一位代表(他的秘书或其他人)在一次重要会议上为他的团队订午餐。他只是简单地说:“嘿,朱迪,我们需要 5 个人的午餐,这就是他们想要的”,然后朱迪接受了这些信息并做任何需要做的事情来获得午餐。 谢谢 Jacob 和 Flash84x....逻辑很清楚..我只是想知道如何使用它... :)【参考方案2】:

我认为您需要了解Delegate Pattern。它是 iphone/ipad 应用程序使用的核心模式,如果您不了解它,您将不会走得太远。我刚刚使用的 wikipedia 链接概述了该模式并给出了它的使用示例,包括 Objective C。这将是一个开始的好地方。还可以看看Overview tutorial from Apple,它是特定于 iPhone 的,还讨论了委托模式。

【讨论】:

以上是关于代表声明困境的主要内容,如果未能解决你的问题,请参考以下文章

SS 在 React 组件声明中代表啥?

蒜头君救人

面对失败与困境保持更强的韧性

virtualenv系列 · 导致Python多版本依赖困境的根源

代表 - 保留或分配 - 释放?

“L”的 Swift 数据类型代表啥?