我正在构建一个简单的聊天室应用程序,其中有一个 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/