在单个 NSOperationQueue iOS 中管理多个操作,例如暂停/恢复单个操作 [英] Managing Multiple Operations in Single NSOperationQueue iOS like Pause/Resume single Operation
问题描述
在我的代码中,我想单独处理队列中的操作,并且能够暂停和恢复队列中的操作操作.我该如何实现?
In my code I want to handle operations individually in a queue and be able to pause and resume the operations operation in the queue. How can I implement that ?
让我简要解释一下我的问题,我使用以下代码通过子类 NSOperation 创建操作并将此操作添加到 NSOperationQueue.
Let me explain my question in brief, I have used below code for creating operation by subclass NSOperation and added this operation to NSOperationQueue.
@interface MyLengthyOperation: NSOperation
@end
@implementation MyLengthyOperation
- (void)main
{
// a lengthy operation
@autoreleasepool
{
for (int i = 0 ; i < 10000 ; i++)
{
// is this operation cancelled?
if (self.isCancelled)
break;
NSLog(@"%f", sqrt(i));
}
}
}
@end
我已经创建了上面的操作,我用
I have created above operation and I am calling it with
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
myQueue.name = @"Download Queue";
myQueue.maxConcurrentOperationCount = 4;
[myQueue addOperation:operation];
现在我想暂停并继续我的操作.让我们假设循环在 6786 上并且我按下了暂停按钮,那么队列应该暂停这个操作,当我按下开始时,它应该从 6786 开始.
Now I want to pause and resume my operation. Lets suppose that the loop is on 6786 and I pressed the pause button, then the queue should pause this operation and when I press start then it should start from 6786.
我想控制队列中的多个操作.我该怎么做?
I want to control multiple operations in the queue. How can I do that ?
我查看了 [queue setSuspended:YES];
- 这将阻止队列添加新操作,但我想控制队列中的现有操作.
I looked at [queue setSuspended:YES];
- this will prevent the queue from adding new operations but I want to control existing operations in queue.
等待您的答复.
提前致谢!
推荐答案
没有内置的暂停特定 NSOperation 的能力,如果你想要这种行为,那么你需要自己构建它.
The is no in-built ability to pause a particular NSOperation, if you want this behaviour then you need to build it yourself.
您可以使用 NSCondition
来执行此操作 -
You can use an NSCondition
to do this -
@interface MyLengthyOperation: NSOperation
@property (atomic) BOOL paused;
@property (nonatomic,strong) NSCondition *pauseCondition;
@end
@implementation MyLengthyOperation
-(instancetype) init {
if (self=[super init]) {
self.pauseCondition=[NSCondition new];
}
return self;
}
- (void)main
{
// a lengthy operation
@autoreleasepool
{
for (int i = 0 ; i < 10000 ; i++)
{
// is this operation cancelled?
if (self.isCancelled)
break;
[self.pauseCondition lock];
while (self.paused) {
[self.pauseCondition wait];
}
NSLog(@"%f", sqrt(i));
[self.pauseCondition unlock];
}
}
}
-(void)pause {
[self.pauseCondition lock];
self.paused=YES;
[self.pauseCondition signal];
[self.pauseCondition unlock];
}
-(void)resume {
[self.pauseCondition lock];
self.paused=NO;
[self.pauseCondition signal];
[self.pauseCondition unlock];
}
777441end
然后你可以说[myOperation pause]
和[myOperation resume]
这篇关于在单个 NSOperationQueue iOS 中管理多个操作,例如暂停/恢复单个操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!