首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSOperationQueue顺序

NSOperationQueue顺序
EN

Stack Overflow用户
提问于 2014-01-10 04:26:42
回答 1查看 96关注 0票数 0

我尝试创建一个用于下载一些文件的队列,所以我创建了一个NSOperation子类,然后创建了队列,在队列的末尾我想发送一个通知,问题是在队列完成之前我在控制台中看到了endQueue日志。

日志是这样的:

代码语言:javascript
复制
....
Download finished
Download finished
Download finished
Queue finished
Download finished
Download finished
Download finished
...

当我需要

代码语言:javascript
复制
....
Download finished
Download finished
Download finished
Download finished
Download finished
Download finished
Queue finished

这是我的NSOperation子类

代码语言:javascript
复制
- (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];
                               }
                           }];
}

在另一个类中,我以这种方式创建和执行队列

代码语言:javascript
复制
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];
}];
EN

回答 1

Stack Overflow用户

发布于 2014-01-23 20:00:36

您可以尝试这样做:

代码语言:javascript
复制
- (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方法中观察通知:

代码语言:javascript
复制
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [notificationCenter postNotificationName:@"Download finished" object:nil];
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21030420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档