iPhone - 从 NSOperation 返回
我正在使用 NSOperation 的子类来执行一些后台进程。我希望当用户单击按钮时取消操作。
这是我的 NSOperation 子类的样子
- (id)init{
self = [super init];
if(self){
//initialization code goes here
_isFinished = NO;
_isExecuting = NO;
}
return self;
}
- (void)start
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
//operation goes here
}
- (void)finish{
//releasing objects here
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
- (void)cancel{
[self willChangeValueForKey:@"isCancelled"];
[self didChangeValueForKey:@"isCancelled"];
[self finish];
}
这就是我如何将此类的对象添加到队列并侦听 KVO 通知
operationQueue = [[NSOperationQueue alloc] init]; [操作队列设置最大并发操作计数:5]; [操作队列addObserver:self forKeyPath:@“操作”选项:0上下文:&OperationsChangedContext];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == &OperationsChangedContext) {
NSLog(@"Queue size: %u", [[operationQueue operations] count]);
}
else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
要取消操作(例如单击按钮),我尝试调用 -cancel 但没有什么区别。还尝试调用 -finish 但即使这样也不会改变任何东西。
每次我向队列添加操作时,队列大小只会增加。 finish 被调用(使用 NSLog 语句检查),但它并没有真正结束操作。我仍然不太有信心我做对了
有人可以告诉我哪里出错了吗?
多谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自NSOperation类参考:
即
cancel
方法实际上并不取消操作,除非您的实现强制执行此操作。再次,来自相关的 部分:From the NSOperation Class Reference:
i.e. the
cancel
method does not actually cancel the operation unless your implementation enforces this. Again, from the relevant section:您只需要执行以下操作即可实现它:
在您的 NSOperation 子类中,添加到 main 方法
在 GUI 类中,您需要为您的 NSOperation 子类添加一个实例变量,并在管理按钮的方法中取消您的 NSOperation 子类。例如:
You just need the following to achieve it:
In your NSOperation subclass, add to main method
In the GUI class, you need an instance variable to your NSOperation subclass, and in the method that manages the button, you cancel your NSOperation subclass. For instance: