OGeek|极客世界-中国程序员成长平台

标题: ios - 从另一个 View Controller 停止 dispatch_async 内的无限循环 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 10:58
标题: ios - 从另一个 View Controller 停止 dispatch_async 内的无限循环

我正在构建一个简单的聊天室应用程序,其中我有一个 NSURLConnection sendSynchronousRequest:将请求发送到服务器,例如长轮询。我想在后台运行时向我的用户显示一个持续更新聊天提要的流。

我的应用程序还允许用户更改他们的聊天室,因此我需要关闭一个 NSURLConnection 并为相应的提要打开另一个。

我目前的实现如下:

//in ViewController.m

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(concurrentQueue, ^{
            while (longPollBOOL){
            NSArray *MSG = [self.currentChatFeed longPoll]; //infinitely call longPoll method
                dispatch_sync(dispatch_get_main_queue(), ^{
                    if (MSG.count != 0) //if the longPoll method returns a non-empty array, stick it into the message feed on the device.
                    {
                        for (id element in MSG)
                        {
                            [self.messages addObject:element];
                            [self finishReceivingMessage];
                        }
                    }
                });
            }

        });

我试图通过设置我的 BOOL = NO 来终止 while 循环,但它不起作用。应用程序中的另一个 View Controller 正在发送 BOOL = NO。我想保证在开始另一个聊天室的另一个无限循环之前停止这个循环。

我想在开始另一个长轮询进程之前终止一个给定聊天室的这个长轮询进程。有什么想法吗?

我这样做对吗?



Best Answer-推荐答案


如果您想要一个可取消的任务,您最好使用 NSOperation 对其进行建模。您可以轻松地做到这一点,而无需子类化:

NSBlockOperation *blockOperation = [[NSBlockOperation alloc] init];

__weak __typeof(blockOperation) weakBlockOperation = blockOperation;

[blockOperation addExecutionBlock:^{
  while (!weakBlockOperation.isCancelled) {
    NSArray *MSG = [self.currentChatFeed longPoll]; //infinitely call longPoll method
    dispatch_sync(dispatch_get_main_queue(), ^{
      if (MSG.count > 0) {
        for (id element in MSG) {
          [self.messages addObject:element];
          [self finishReceivingMessage];
        }
      }
    });
  }
}];

[queue addOperation:blockOperation];

您只需要保留对您的操作的引用,您可以随时取消它。

关于ios - 从另一个 View Controller 停止 dispatch_async 内的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072080/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4