ios - 取消的操作仍在运行
<p><p>我需要取消操作队列中的所有操作。但在调用 cancelAllOperation 方法后,操作仍在运行。
简单的例子:</p>
<pre><code>@interface MyOperation : NSOperation
@end
@implementation MyOperation
-(void)main {
NSLog(@"starting 1");
sleep(4);
NSLog(@"finished 1");
}
@end
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
;
NSOperationQueue *queue = [ init];
MyOperation *op = ;
;
sleep(2);
;
NSLog(@"canceled");
}
log:
2014-07-23 09:55:48.839 MDict1 starting 1
2014-07-23 09:55:50.842 MDict1 canceled
2014-07-23 09:55:52.842 MDict1 finished 1
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>取消操作不会唤醒 <code>sleep</code> 调用。在 <code>viewDidLoad</code> 中调用 <code>sleep</code> 是不好的。永远不要在主线程上休眠。</p>
<p>正确的解决方案是你的操作的<code>main</code>方法的实现需要检查<code>self</code>是否已经被取消。如果是,则需要返回。</p>
<p>一个粗略的例子可能是:</p>
<pre><code>- (void)main {
while (!self.isCancelled) {
// do some repeated operation
}
}
</code></pre>
<p>同样,当它看到它已被取消时,它有责任停止自己的操作。队列实际上并没有杀死任何操作。</p>
<p>来自 <code>NSOperationQueue cancelAllOperations</code> 的文档(强调我的):</p>
<blockquote>
<p>This method sends a cancel message to all operations currently in the queue. Queued operations are cancelled before they begin executing. <strong>If an operation is already executing, it is up to that operation to recognize the cancellation and stop what it is doing.</strong></p>
</blockquote></p>
<p style="font-size: 20px;">关于ios - 取消的操作仍在运行,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/24901402/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/24901402/
</a>
</p>
页:
[1]