草庐IT

iOS 在关闭 ViewController 时停止 for 循环中的所有当前处理

coder 2024-01-19 原文

我正在使用下面的代码,该代码在嵌入了 UITableViewUIViewController 中调用。 它遍历位置列表,创建 NSURL 并将其传递给 NSXMLParser。一切都按预期工作。

但是,我希望如果用户点击后退按钮,那不仅是 UIViewController 被取消,而且用户返回到我之前的 UIViewController已经,但我希望立即终止与 -(void)getInfoNSXMLParser 中发生的 for 循环 相关的处理如果它确实还在运行。

在大多数情况下,处理会完成,这不是问题,但是,在某些情况下,这可能需要更长的时间,我不希望代码在按下后继续运行,因为那时不需要数据,因此只会浪费资源,并且由于处理多个 NSURL s 可能会在返回到先前的 UIViewController 时阻塞 UI。

-(void)getInfo{
    NSDictionary *places = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"places" ofType:@"plist"]];
    NSArray *placescc = [[NSArray alloc] initWithArray:places.allKeys];
    __block NSUInteger placewaiting = placescc.count;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *savedLocs = [[defaults objectForKey:@"savedLocs"]mutableCopy]; //got savedLocs
    NSDictionary *thisLoc = [[savedLocs objectForKey:_LocId]mutableCopy]; //got this Loc

    lastInfoCount = 0; // set default
    if ([[thisLoc objectForKey:@"Infos"]count]){
        lastInfoCount = [[thisLoc objectForKey:@"Infos"]count]; // set saved count if we have one
    }

    for (NSString *place in placescc) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://url.com/%@/%@",place, LocIdString]];
            NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

            dispatch_async(dispatch_get_main_queue(), ^{
                [parser setDelegate:self];
                [parser setShouldResolveExternalEntities:NO];
                [parser parse];

                placewaiting = placewaiting-1;
                if (placewaiting == 0){

                    [self.tableView reloadData];
                    [self.activityIndicator stopAnimating];
                    lastRefresh = [NSString stringWithFormat:@"%@",[NSDate date]];
                }
            });
        });
    }
}

最佳答案

我建议使用 NSOperationQueue 和 NSBlockOperation,然后您可以在 dealloc(或可能是 viewWillDisappear)和在 GCD 线程测试 isCanceled 上执行的 block 中取消操作并退出/跳过 UI 更新。但是,您必须确保对 View Controller 的弱引用,否则执行 block 将保留 Controller 。像这样:

// @property(nonatomic,weak) NSBlockOperation *backgroundOperation;

+ (NSOperationQueue*)operationQueue
{
    static dispatch_once_t onceToken;
    static NSOperationQueue *operationQueue;
    dispatch_once(&onceToken, ^{
        operationQueue = [[NSOperationQueue alloc] init];
    });

    return operationQueue;
}

- (NSOperationQueue*)operationQueue
{
    return [[self class] operationQueue];
}

- (void)dealloc
{
    [self.backgroundOperation cancel];
}

- (void)getInfo
{
    NSDictionary *places = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"places" ofType:@"plist"]];
    NSArray *placescc = [[NSArray alloc] initWithArray:places.allKeys];
    __block NSUInteger placewaiting = placescc.count;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *savedLocs = [[defaults objectForKey:@"savedLocs"]mutableCopy]; //got savedLocs
    NSDictionary *thisLoc = [[savedLocs objectForKey:_LocId]mutableCopy]; //got this Loc

    lastInfoCount = 0; // set default
    if ([[thisLoc objectForKey:@"Infos"]count]){
        lastInfoCount = [[thisLoc objectForKey:@"Infos"]count]; // set saved count if we have one
    }

    // Ensure previous operation finished
    [self.backgroundOperation cancel];

    NSBlockOperation *op = [[NSBlockOperation alloc] init];
    self.backgroundOperation = op;
    __weak NSBlockOperation *weakOp = op;
    __weak typeof(self) weakSelf = self;

    [op addExecutionBlock:^{
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://url.com/%@/%@",place, LocIdString]];
        NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
        if (weakOp && !weakOp.isCancelled)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                [parser setDelegate:weakSelf];
                [parser setShouldResolveExternalEntities:NO];
                [parser parse];

                placewaiting = placewaiting-1;
                if (placewaiting == 0){

                    [weakSelf.tableView reloadData];
                    [weakSelf.activityIndicator stopAnimating];
                    lastRefresh = [NSString stringWithFormat:@"%@",[NSDate date]];
                }
            });
        }
    }];

    [[self operationQueue] addOperation:op];
}

请注意,weakSelf、weakOp 和 backgroundOperation 属性将在其引用的对象被释放时自动为 null,因此如果 UI 更新 block 中的代码在 View Controller 关闭后执行,weakSelf.tableView/activityIndi​​cator 将为 null 且无操作。在您的情况下,因为大部分工作是同步检索和解析数据,因此不会中止,但上面的代码意味着 View Controller 将立即释放,并且 View Controller 上的 UI 更新变为空操作。

关于iOS 在关闭 ViewController 时停止 for 循环中的所有当前处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23492250/

有关iOS 在关闭 ViewController 时停止 for 循环中的所有当前处理的更多相关文章

  1. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  2. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  3. ruby-on-rails - form_for 中不在模型中的自定义字段 - 2

    我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢

  4. ruby-on-rails - 跳过状态机方法的所有验证 - 2

    当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested

  5. ruby - Nokogiri 剥离所有属性 - 2

    我有这个html标记:我想得到这个:我如何使用Nokogiri做到这一点? 最佳答案 require'nokogiri'doc=Nokogiri::HTML('')您可以通过xpath删除所有属性:doc.xpath('//@*').remove或者,如果您需要做一些更复杂的事情,有时使用以下方法遍历所有元素会更容易:doc.traversedo|node|node.keys.eachdo|attribute|node.deleteattributeendend 关于ruby-Nokog

  6. ruby-on-rails - Rails 中的 NoMethodError::MailersController#preview undefined method `activation_token=' for nil:NilClass - 2

    似乎无法为此找到有效的答案。我正在阅读Rails教程的第10章第10.1.2节,但似乎无法使邮件程序预览正常工作。我发现处理错误的所有答案都与教程的不同部分相关,我假设我犯的错误正盯着我的脸。我已经完成并将教程中的代码复制/粘贴到相关文件中,但到目前为止,我还看不出我输入的内容与教程中的内容有什么区别。到目前为止,建议是在函数定义中添加或删除参数user,但这并没有解决问题。触发错误的url是http://localhost:3000/rails/mailers/user_mailer/account_activation.http://localhost:3000/rails/mai

  7. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  8. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  9. ruby-on-rails - 如何重命名或移动 Rails 的 README_FOR_APP - 2

    当我在我的Rails应用程序根目录中运行rakedoc:app时,API文档是使用/doc/README_FOR_APP作为主页生成的。我想向该文件添加.rdoc扩展名,以便它在GitHub上正确呈现。更好的是,我想将它移动到应用程序根目录(/README.rdoc)。有没有办法通过修改包含的rake/rdoctask任务在我的Rakefile中执行此操作?是否有某个地方可以查找可以修改的主页文件的名称?还是我必须编写一个新的Rake任务?额外的问题:Rails应用程序的两个单独文件/README和/doc/README_FOR_APP背后的逻辑是什么?为什么不只有一个?

  10. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

随机推荐