2010-12-06 72 views
1

我很困惑 - 我不明白代表是什么意思?委托声明困境

的应用程序,它是默认创建的代表是可以理解的,但在某些情况下,我已经看到了这样的事情:

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

//... 

@end 

什么是<UIScrollViewDelegate>呢?

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

回答

12

<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 
+4

为了进一步澄清雅各布的回应...你使用委托的原因是要分配一个类来处理UIScrollView对象依赖的特定任务来正确地工作。用外行人的话说,你可以把它看作是一个私人助理。一位老板太忙了,无法关心午餐的订购方式,因此他有一位代表(他的秘书或其他),他要求他在一次重要会议上为他的团队订购午餐。他只是说:“嗨朱迪,我们需要5人的午餐,这是他们想要的东西”,朱迪然后拿着这些信息,做任何需要做的事情来获得午餐。 – 2010-12-06 06:39:45

2

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