2012-02-22 100 views
0

我想了解委託模式是如何工作的。下面是我嘗試過的一些代碼,但問題是代理方法downloadStarted和downloadFinished從不調用。委託模式

我在這裏想念什麼?

DownloaderDelegate.h

@protocol DownloaderDelegate <NSObject> 
-(void)downloadStarted; 
-(void)downloadFinished; 
@end 

Downloader.h

#import "DownloaderDelegate.h" 

@interface Downloader : NSObject 

@property (nonatomic, retain) id<DownloaderDelegate>delegate; 
-(void)fileIsDownloaded; 
-(void)downloadFile; 
@end 

Downloader.m

@implementation Downloader 
@synthesize delegate = _delegate; 


-(void)downloadFile 
{ 
    [[self delegate] downloadStarted]; 

    [NSTimer timerWithTimeInterval:5 
          target:self 
          selector:@selector(fileIsDownloaded) 
          userInfo:nil 
          repeats:NO]; 
} 


-(void)fileIsDownloaded 
{ 
    [[self delegate]downloadFinished]; 
} 
@end 

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
    { 
     .... 
     Downloader *d = [[Downloader alloc]init]; 
     [d downloadFile]; 
     [d release]; 
     .... 
    } 

-(void)downloadStarted 
{ 
    NSLog(@"Started"); 
} 

-(void)downloadFinished 
{ 
    NSLog(@"Finished"); 
} 
+1

閱讀本 - [代表和數據源(https://developer.apple.com/ library/mac/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#// apple_ref/doc/uid/TP40002974-CH7-SW18) – beryllium 2012-02-22 08:33:37

回答

3

AppDelegate,需要實現DownloaderDelegate協議:

@interface AppDelegate : NSObject <UIApplicationDelegate,DownloaderDelegate>

,然後,當你實例化下載,使AppDelegate其委託。

d.delegate = self;

+0

是的,我忘了添加[d setDelegate:self]。謝謝 ! – foho 2012-02-22 08:25:07

0

首先,你改變你的委託,以「分配」的屬性,它並不需要reatin。 然後設置d.delegate = self;(或您需要的班級)。然後只有您可以訪問該班級的代表。 在您需要委託類的.h文件中,你必須包括委託 如:

@interface AppDelegate : NSObject<UIApplicationDelegate,DownloaderDelegate>