ios - 从另一个 View Controller 停止dispatch_async内部的无限while循环

标签 ios objective-c nsurlconnection grand-central-dispatch long-polling

我正在构建一个简单的聊天室应用程序,其中有一个 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 循环,但它不起作用。 BOOL = NO 是由应用程序中的另一个 View Controller 发送的。我想保证在开始另一个聊天室的另一个无限循环之前停止此循环。

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

我这样做正确吗?

最佳答案

如果您想要一个可取消的任务,您最好使用 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内部的无限while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072080/

相关文章:

c++ - 如何在不在 .h 文件中制作原型(prototype)的情况下将 Objective-C++ 类公开给 swift

ios - 使用 UIPageViewController 创建网格/ map

iphone - 要求 iOS 重新加载 ui 或刷新它

ios - Alamofire 4.0.0 : [String:String] is not convertible to [String : Any] & Request is ambiguous without more context

ios - -[UIThreadSafeNode canPerformAction :withSender:]: unrecognized selector sent to instance

ios - 从远程 URL 下载视频到设备并通过 AVPlayer 流式传输

ios - 如何在 Imgur 用户线上发布图像

ios - NSURLConnection(initWithRequest 与 sendAsyncRequest)

ios - 倒计时错误(NSDate 和 Objective-C)

ios - 如何阻止 UITableView 更新 contentSize