我尝试创建一个用于下载一些文件的队列,所以我创建了一个NSOperation子类,然后创建了队列,在队列的末尾我想发送一个通知,问题是在队列完成之前我在控制台中看到了endQueue日志。
日志是这样的:
....
Download finished
Download finished
Download finished
Queue finished
Download finished
Download finished
Download finished
...当我需要
....
Download finished
Download finished
Download finished
Download finished
Download finished
Download finished
Queue finished这是我的NSOperation子类
- (id) initWithDictionary:(NSDictionary*)dict {
self = [super init];
if (self) {
[self setFileDict:dict];
}
return self;
}
- (void) main {
[self runOperation];
}
- (void) runOperation {
NSURL *urlFile = [NSURL URLWithString:[fileDict objectForKey:@"urlStr"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:urlFile]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error){
if (data) {
[data writeToFile:pathFile atomically:YES];
[notificationCenter postNotificationName:@"Download finished" object:nil];
}
}];
}在另一个类中,我以这种方式创建和执行队列
self.operationQueue = [[NSOperationQueue alloc] init];;
[self.operationQueue setMaxConcurrentOperationCount:1];
for (NSDictionary *dict in fileDaScaricare) {
DownloadOperation *downloadOperation = [[DownloadOperation alloc] initWithDictionary:dict];
[self.operationQueue addOperation:downloadOperation];
}
[self.operationQueue addOperationWithBlock:^{
NSLog(@"Queue finished");
[notificationCenter postNotificationName:@"endFile" object:nil];
}];发布于 2014-01-23 20:00:36
您可以尝试这样做:
- (void) runOperation {
NSURL *urlFile = [NSURL URLWithString:[fileDict objectForKey:@"urlStr"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:urlFile];
self.downloadConnection = [[NSURLConnection alloc] initWithRequest:downloadRequest delegate:self];
// keeps the NSOperation alive for the during of the NSURLConnection!
[self.downloadConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[self.downloadConnection start];
}然后,您可以在NSURLConnectionDelegate方法中观察通知:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[notificationCenter postNotificationName:@"Download finished" object:nil];
}https://stackoverflow.com/questions/21030420
复制相似问题