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