我有一个有 5 NSOperations
的队列。队列的setMaxConcurrentOperationCount
设置为 1。每个操作基本上都是对服务器下载特定文件的调用。
仅当文件保存到磁盘时,跟踪一个文件的下载是否已完成以启动另一个NSOperation
的最佳方法是什么?或者有没有办法让NSOperations
知道文件的下载进度?
您可以简单地子类NSOperation
并将用于下载数据并将其保存到文件系统的代码放入NSOperation
子类的-main
方法中 操作完成后,NSOperationQueue
中的下一个操作将自动开始执行
@implementation MyOperation
- (void) main {
if ([self isCancelled]) {
NSLog(@"** operation cancelled **");
} else {
NSURL *conUrl = [NSURL URLWithString: urlString];
NSError *error;
NSData *conData = [NSData dataWithContentsOfURL: conUrl options: NSDataReadingMappedIfSafe error: & error];
if (!error) {
UIImage *image = [
[UIImage alloc] initWithData: conData];
NSString *cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
NSString *jpgFilePath = [NSString stringWithFormat: @"%@/%@.jpg", cacheDir, textLabel];
conData = [NSData dataWithData: UIImageJPEGRepresentation(image, 1.0f)];
[conData writeToFile: jpgFilePath atomically: YES];
}
}
NSLog(@"Operation finished");
}
@end
您应该
重写NSOperation
子类中的isFinished
方法,以便仅在实际完成时才返回YES
。