Asynchronous NSOperationQueue顺序

Asynchronous NSOperationQueue顺序,asynchronous,download,nsoperation,nsoperationqueue,Asynchronous,Download,Nsoperation,Nsoperationqueue,我尝试为下载一些文件创建一个队列,所以我创建了一个NSOperation子类,然后创建了队列,在队列的末尾我想发送一个通知,问题是我在队列完成之前在控制台中看到了endQueue日志 日志如下所示: .... Download finished Download finished Download finished Queue finished Download finished Download finished Download finished ... 而我需要 .... Downloa

我尝试为下载一些文件创建一个队列,所以我创建了一个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
这是我的操作子类

- (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];
}];
您可以尝试以下方法:

- (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];        
}
然后,您可以在NSURLConnectionLegate方法中观察通知:

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [notificationCenter postNotificationName:@"Download finished" object:nil];
}