2014-01-09 62 views
0

我嘗試創建一個隊列用於下載一些文件,所以我創建了一個NSOperation子類然後是隊列,在隊列的最後我想發送一個通知,問題是我看到控制檯的endQueue隊列完成前的日誌。NSOperationQueue命令

日誌是這樣的:

.... 
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]; 
}]; 

回答

1

你可以試試這個:

- (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]; 
}