2010-12-06 73 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的,並且還討論了委託模式。