4

我正在使用 ASIHTTPRequest 和 NSOperationQueue 从不同的链接下载数据

在后台线程中下载。当请求完成时,我使用 requestFinished 解析

ASIHTTPRequest 的委托方法。当所有请求都在时,我想更新 tableview 中的数据

队列已完成。有什么方法可以知道 NSOperationQueue 何时处理了所有

要求?我的意思是队列有任何变量,如“isEmpty”或任何委托方法,如“queueDidCompletedAllOperation”?

请帮忙。

这是代码:

//source

@interface SourceModel : NSObject

@property (nonatomic, retain) NSString * link;

@property (nonatomic, retain) NSString * name;

@end


//for rssGroup

@interface CompleteRSSDataModel : NSObject

@property (nonatomic,strong) SourceModel * source;

@property (nonatomic,strong) KissXMLParser * parser;

@property (nonatomic,strong) NSArray * rssArticles;

@end

- (void)viewDidLoad
{
       for (int index=0; index<[rssGroups count]; index++) {

            NSString * urlString = [[[rssGroups objectAtIndex:index] source] link];

            NSURL *url = [NSURL URLWithString:urlString];

            ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; [request setDelegate:self];

            //set this request's tag to group index of this source(link). See requestFinished for use of this :)
            [request setTag:index];

            [self.queue addOperation:request];
        }

}


- (void)requestFinished:(ASIHTTPRequest *)request {

    NSLog(@"%@",@"RSS Data got from internet successfully :))");


    int groupIndex = [request tag];

    CompleteRSSDataModel * group = [rssGroups objectAtIndex:groupIndex];

    group.parser = [[KissXMLParser alloc]initWithData:[request responseData]];

    if (group.parser == nil) {

        NSLog(@"%@",@"Failed - Error in parsing data :((");
    }

    else {
        NSLog(@"%@",@"Data Parsed successfully :))");

        group.rssArticles = [group.parser itemsInRss];

        //So i want to check here that queue is empty, reload data, but as my information, i don't know any method like hasCompletedAllRequested 

        //if(self.queue hasCompletedAllRequests) {

        //     [self.tableview reloadData];
        //}


    }
}

- (void)requestFailed:(ASIHTTPRequest *)request {

    NSLog(@"%@",@"Error in Getting RSS Data from internet:((");

}
4

3 回答 3

10

如果所有操作都已完成,则operations数组计数将为零。

要检查这一点,您可以使用键值观察编码来operations观察NSOperationQueue

为键设置观察者opertions如下:

[self.queue addObserver:self forKeyPath:@"operations" options:0 context:NULL];

然后在您的 observeValueForKeyPath 中执行此操作,如下所示:

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                         change:(NSDictionary *)change context:(void *)context
{
    if (object == self.queue && [keyPath isEqualToString:@"operations"]) {
        if ([self.queue.operations count] == 0) {
            // Do something here when all operations has completed
            NSLog(@"queue has completed");
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object 
                               change:change context:context];
    }
}

在 iOS 4.0 之后,您可以使用属性operationCountlikeself.queue.operationCount == 0而不是像这样检查[self.queue.operations count] == 0

于 2012-08-11T05:27:17.480 回答
2

我知道这已经得到解答,但是对于未来的读者,如果您使用的是AFNetworking,更具体地说是AFHTTPRequestOperation ,您可以执行以下操作:

NSString *urlPath = [NSString stringWithFormat:@"%@%@", baseUrl, file];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlPath]];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[operation setCompletionBlockWithSuccess:
 ^(AFHTTPRequestOperation *operation, id responseObject) {
   if ([[queue operations] count] ==0) {
       NSNotification * success = [NSNotification notificationWithName:@"TotalDone" object:[NSNumber numberWithBool: YES]];
      [[NSNotificationCenter defaultCenter] postNotification:success];
      queueSize = 0;
   } else {

       //get total queue size by the first success and add 1 back
       if (queueSize ==0) {
           queueSize = [[queue operations] count] +1.0;
       }
       float progress = (float)(queueSize-[[queue operations] count])/queueSize;
       NSNumber * totProgress = [NSNumber numberWithFloat:progress];
       NSNotification * totalProgressNotification = [NSNotification notificationWithName:@"TotalProgress"
                                                                                           object:totProgress];
       [[NSNotificationCenter defaultCenter] postNotification:totalProgressNotification];
   }


} failure:^(AFHTTPRequestOperation *operation, NSError *error) 
        NSLog(@"Error: %@", error);
        }];

这适用于将下载添加到 NSOperationQueue 的下载器,然后通知两个进度条:1 个用于文件进度,1 个用于总进度。

希望这可以帮助

于 2013-02-20T01:15:35.317 回答
0

我有几个选择:

  1. 改用ASINetworkQueue和 set queueDidFinishSelector,所以它会告诉你什么时候完成。这也使您有机会不仅更新UIProgressView单个行的视图,还可以更新整个下载过程的另一个视图。

  2. 你能添加一些东西来NSOperationQueue简单地调用一个方法来更新你的 UI(当然是在主队列中)吗?通过将它添加到队列中,它不会到达它,直到它清除队列。或者在另一个队列中调用waitUntilFinished,此时您可以更新您的 UI。

  3. 查看您的评论,您似乎正在更新您的 UI requestFinished,但不满意,因为您认为等待所有更新发生可能会更好。就个人而言,我更喜欢逐个请求更新 UI,这样如果速度很慢,你会得到临时反馈,而不是等待一切。这必须优雅地完成,但我喜欢在进行过程中更新 UI。诚然,有些流程不适合这样做。

关于最后一点,我认为诀窍是进行这些更新,以免分散注意力。具体来说,如果您的 UI 是 a UITableView,您可能不想执行 a tableView.reloadData,这将重新加载整个表格。相反,您可能想检查单元格是否仍在加载(通过方法cellForRowAtIndexPath,不要与方法UITableView混淆),如果是,则更新该行,例如:UITableViewControllertableView:cellForRowAtIndexPath

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell)
{
    // you can either update the controls in the cell directly, or alternatively, just
    // call reloadRowsAtIndexPaths to have the tableView use your data source:

    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
                          withRowAnimation:UITableViewRowAnimationFade];
}
于 2012-08-11T05:13:01.453 回答