代表宣言进退两难

时间:2010-12-06 06:24:46

标签: ios objective-c cocoa-touch cocoa cocoa-design-patterns

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

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

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

//...

@end

<UIScrollViewDelegate>是什么?

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

2 个答案:

答案 0 :(得分:12)

<UIScrollViewDelegate>表示类符合 UIScrollViewDelegate 协议

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

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

@implementation MyClass : UIViewController <SomeProtocol, SomeOtherProtocol>

使类符合协议的目的是:a)将类型声明为协议的符合,因此您现在可以在id <SomeProtocol>下对此类型进行分类,这对于此对象的委托对象更好class可能属于,和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

答案 1 :(得分:2)

我认为您需要了解Delegate Pattern。它是iphone / ipad应用程序使用的核心模式,如果你不理解它,你就不会走得太远。我刚刚使用的维基百科链接概述了模式,并给出了它的使用示例,包括Objective C.这将是一个开始的好地方。另外,请看一下特定于iPhone的Overview tutorial from Apple,并讨论代表模式。

相关问题