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");
}
Your
AppDelegateneeds to implement theDownloaderDelegateprotocol:@interface AppDelegate : NSObject <UIApplicationDelegate,DownloaderDelegate>and then, when you instantiate the downloader, make the
AppDelegateits delegate.d.delegate = self;