我正在尝试了解委托模式的工作原理。下面是我尝试过的一些代码,但问题是委托方法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");
}
答案 0 :(得分:3)
您的AppDelegate
需要实施DownloaderDelegate
协议:
@interface AppDelegate : NSObject <UIApplicationDelegate,DownloaderDelegate>
然后,当您实例化下载程序时,请将AppDelegate
作为其委托。
d.delegate = self;
答案 1 :(得分:0)
首先,您将代理的属性更改为“分配”,它不需要reatin。 然后设置 d.delegate = self;(或您需要的类)。然后只有您可以访问该类的委托。 在您需要委托的类的.h文件中,您必须包含委托 例如:
@interface AppDelegate : NSObject<UIApplicationDelegate,DownloaderDelegate>