我正在使用NSOperation队列来获取图像并在我的tableview单元格中显示它们。在图像返回之前,我会显示加载叠加层,一旦操作完成,它就会暗示委托,然后我删除加载叠加层。
现在,我想在说出5秒之后超时获取操作并删除加载覆盖,但是基于计时器的方法没有用完。请建议。
以下是我的代码:
#import "MyImageFetchOperation.h"
#import "MyImageFetchController.h"
#import "MyHTTPRequest.h"
@interface MyImageFetchOperation ()
@property (nonatomic, strong) NSString *imageURL;
@property (nonatomic, weak) id <MyOperationCompletedDelegate> delegate;
@property (nonatomic, assign) BOOL isCompleted;
@property (nonatomic, weak) NSTimer *timeoutTimer;
@end
@implementation MyImageFetchOperation
@synthesize imageURL;
@synthesize delegate;
@synthesize isCompleted;
#define kMyImageFetchTimeout 5
#pragma mark -
#pragma mark Destruction
- (void)dealloc {
self.delegate = nil;
}
- (id)initWithImageURL:(NSString *)iImageURL delegate:(id)iDelegate {
if (self = [super init]) {
self.imageURL = iImageURL;
self.delegate = iDelegate;
}
return self;
}
- (void)main {
self.isCompleted = NO;
NSMutableURLRequest *aRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.imageURL]];
[aRequest setTimeoutInterval:kMyImageFetchTimeout];
[aRequest setHTTPMethod:@"GET"];
self.timeoutTimer = [NSTimer scheduledTimerWithTimeInterval:kMyImageFetchTimeout target:self selector:@selector(requestTimedOut) userInfo:nil repeats:NO];
[NSURLConnection sendAsynchronousRequest:aRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *iData, NSError *iConnectionError) {
if (!self.isCompleted) {
if (iConnectionError) {
[[MyImageFetchController sharedRunnerImageFetchControllerMy] urlFailed:self.imageURL];
}
UIImage *anImage = [UIImage imageWithData:iData];
if (anImage) {
[MyUtilities cacheFile:anImage withName:[self.imageURL runnerMD5HashMy] toDirectory:[self.delegate cacheDirectoryForImages]];
} else {
[[MyImageFetchController sharedRunnerImageFetchControllerMy] urlFailed:self.imageURL];
}
[self.delegate operationCompletedForURL:self.imageURL];
self.isCompleted = YES;
}
}];
}
- (void)requestTimedOut {
self.isCompleted = YES;
[self.timeoutTimer invalidate];
self.timeoutTimer = nil;
[[MyImageFetchController sharedRunnerImageFetchControllerMy] urlFailed:self.imageURL];
[self.delegate operationCompletedForURL:self.imageURL];
}
@end
答案 0 :(得分:0)
为什么不打电话
[self.delegate operationCompletedForURL:self.imageURL];
在这个if?
里面if (iConnectionError) {
另一方面,你不应该在该块中使用self,你应该使用__block变量。
答案 1 :(得分:0)
你需要一个运行循环来使你的计时器工作,如下所示:
- (void)main
{
// your code
yourTimer = ... // create your timer
NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
[runLoop addTimer:yourTimer forMode:NSRunLoopCommonModes];
[runLoop run];
}
哦,我想最好在main中设置你自己的自动释放池。