foho
foho

Reputation: 779

Delegate pattern

I'm trying to understand how delegate pattern works. Below is some code that I tried, but the problem is that the delegate methods downloadStarted and downloadFinished are never invoked.

What I miss here ?

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");
}

Upvotes: 0

Views: 574

Answers (2)

Sree
Sree

Reputation: 907

First you change the property of your delegate to "assign", it doesn't need reatin. Then set the d.delegate = self;(or the class you neeeded).then only you can access the delegate at that class. In the .h file of the class where you needed the delegate, you have to include the delegate eg:

@interface AppDelegate : NSObject<UIApplicationDelegate,DownloaderDelegate>

Upvotes: 0

Fran Sevillano
Fran Sevillano

Reputation: 8163

Your AppDelegate needs to implement the DownloaderDelegate protocol:

@interface AppDelegate : NSObject <UIApplicationDelegate,DownloaderDelegate>

and then, when you instantiate the downloader, make the AppDelegate its delegate.

d.delegate = self;

Upvotes: 3

Related Questions