我正在制作一个用于异步下载图像的 OpenSource (github) 助手类(我遇到了很大的麻烦)。
但是,我设置了委托方法来提醒委托图像已完成下载。问题是委托方法没有被调用。我正在设置委托和所有内容,但我不知道为什么会出现问题。
请看我的代码!我只发布了相关代码。
MKAsyncImageDownloader.h
@protocol MKAsyncImageDownloaderDelegate <NSObject>
@required
- (void)imageShouldFinishDownloading;
@end
@interface MKAsyncImageDownloader : NSObject {
id <MKAsyncImageDownloaderDelegate> delegate;
}
- (id) initWithDelegate:(id <MKAsyncImageDownloaderDelegate>) delegat;
@property (retain, nonatomic) id <MKAsyncImageDownloaderDelegate> delegate;
@end
MKAsyncImageDownloader.m
- (id) initWithDelegate:(id<MKAsyncImageDownloaderDelegate>) delegat {
self = [super init];
if (self) {
delegate = delegat;
}
return self;
}
- (void)imageAtURLHasDownloaded:(NSDictionary *)dict {
[downloadedImageArray addObject:[dict objectForKey:@"image"]];
[[self delegate] imageShouldFinishDownloading];
}
MKOperation.m NSOperation 的子类。我 alloc/init MKAsynImageDownloader 只执行选择器。代码:
- (void)start {
UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:self.targetURL]];
if (image) {
NSDictionary *dict = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:image, self.targetURL, nil] forKeys:[NSArray arrayWithObjects:@"image", @"url", nil]];
MKAsyncImageDownloader *downloader = [[MKAsyncImageDownloader alloc] init];
[downloader performSelectorOnMainThread:@selector(imageAtURLHasDownloaded:) withObject:dict waitUntilDone:YES];
[dict release];
[downloader release];
}
[image release];
}
RootViewController.h
MKAsyncImageDownloader *loader;
RootViewController.m 只是为了展示我是如何设置委托的。
loader = [[MKAsyncImageDownloader alloc] initWithDelegate:self];