NSOperation KVO问题 [英] NSOperation KVO problem

查看:77
本文介绍了NSOperation KVO问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下函数在 nsoperationqueue 中的操作完成后通知我的应用程序,以便我可以安排依赖于操作结果的任务.我正在使用:

I'm using following function to get my application notified after the operation in nsoperationqueue has finished, so that I can schedule the task that's dependent upon the result of the operation. I'm using:

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object 
                        change:(NSDictionary *)change 
                       context:(void *)context
{
  if([keyPath isEqual:@"isFinished"] && _operation == object)
  {  
    NSLog(@"Our Thread Finished!");
    [_operation removeObserver:self forKeyPath:@"isFinished"];
    [self performSelectorOnMainThread:@selector(showDialog) withObject:nil waitUntilDone:YES];
  } 
}

我的问题是,由于分配给这些操作的任务大多是解析数据,如果我尝试点击其他按钮或基本上执行一些导致操作的操作,我会收到以下异常:

My question is since mostly the tasks assigned to these operations are parsing of data if I try to tap some other button or basically do something that results in action, I get the following exception:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<Settings: 0x21b970>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: isFinished

我完全理解,因为我尝试在主线程上做其他事情,因此调用主线程:

I perfectly understand that since I try doing other things on main thread, because of which the call to main thread:

[self performSelectorOnMainThread:@selector(showDialog) withObject:nil waitUntilDone:YES];

执行失败.但是这个问题的解决方案是什么,因为我希望允许用户在发出请求后执行任何操作,并在完成分配给操作的任务后执行计划的操作.

fails to get executed. But what's the solution to this problem as I want both allow user do any action after making a request and also perform the action scheduled after finishing the task assigned to the operation.

真的有可能吗?

提前谢谢.

推荐答案

如果您需要 Mac OS X 10.6 Snow Leopard 或(我认为)iPhone OS 3.0,您可以完全避免使用 KVO.只需在主线程上创建一个你想要做的工作的操作,将它需要遵循的操作添加为依赖,然后将主线程操作放到主队列中:

If you can require Mac OS X 10.6 Snow Leopard, or (I think) iPhone OS 3.0, you can avoid KVO entirely for this. Just create another operation for the work you want to do on the main thread, add the operation it needs to follow as a dependency, and then put the main-thread operation on the main queue:

NSBlockOperration *mainThreadOp = [NSBlockOperation blockOperationWithBlock:^{
    [self showDialog];
}];
[mainThreadOp addDependency:backgroundOp];
[[NSOperationQueue mainQueue] addOperation:mainThreadOp];

NSOperation 支持不同队列上的操作之间的依赖关系.请注意不要让不同队列上的操作相互依赖,因为这会导致死锁.

NSOperation supports dependencies between operations on different queues. Just be careful not to make operations on different queues mutually dependent, because that will result in deadlock.

这篇关于NSOperation KVO问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆