ios - observeValueForKeyPath 没有被调用
<p><p>我正在开发一个测试应用程序,其中有一个 NSOperationQueue。我正在创建一个 NSInvocationOperation 并观察该操作的“isFinished”属性。
奇怪的是,observeValueForKeyPath 只是有时被调用。我无法理解每次调用它时必须进行的更改。请帮忙。</p>
<p>这是我写的代码:</p>
<pre><code>-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
........//initialization
queue = ;
operation=;
operation = [initWithTarget:self selector:@selector(CreateOperationWithContext:) object:context];
;
;
..... // launch the view controller
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if () {
NSLog(@"came in");
;
}
else
{
;
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>以下代码对我有用。我从 iOS 单 View 应用程序模板开始。这是我所拥有的:</p>
<pre><code>@implementation SOAppDelegate
{
NSOperationQueue* queue;
NSOperation* operation;
}
- (void)CreateOperationWithContext: (id)foo
{
NSLog(@"Op ran");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
queue = ;
// operation = ; // Commented this out because it's redundant with the next line
operation = [ initWithTarget:self selector:@selector(CreateOperationWithContext:) object:];
;
;
return YES;
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ()
{
NSLog(@"came in");
;
}
else
{
;
}
}
// ... rest of empty default app delegate methods here...
@end
</code></pre>
<p>在控制台中,我看到:</p>
<pre><code>2013-08-13 08:04:15.150 TestOpKVO Op ran
2013-08-13 08:04:21.903 TestOpKVO came in
</code></pre>
<p>所以关于您的 <code>-CreateOperationWithContext:</code> 实现的某些问题正在引起麻烦。也就是说,即使我将操作更改为引发异常,我仍然会看到 KVO 通知被调用。</p>
<p>如果我是你,我会从这个非常基本的、有效的示例开始,然后一步一步调整它以适应你的真实代码,检查每一步以确保通知仍然有效。 </p>
<p><strong>一些提示:</strong>(可能与您看到的问题无关,但使用 KVO 的良好做法)</p>
<p>首先,在您的观察中使用 KVO 上下文。它更安全,更具确定性。见 <a href="https://stackoverflow.com/questions/12719864/best-practices-for-context-parameter-in-addobserver-kvo/14162363#14162363" rel="noreferrer noopener nofollow">answer I wrote over here</a>了解详情。</p>
<p>其次,不要从 <code>-observeValueForKeyPath:</code> (或 <code>-addObserver:...</code> 的调用中调用 <code>-removeObserver:forKeyPath:</code> > 任一)对于被通知的相同 keyPath。这有可能弄乱 KVO 的内部观察者数据结构,并可能导致非确定性崩溃,让您抓狂。见 <a href="https://stackoverflow.com/questions/17097311/locking-exposuremode-with-key-value-observer-causes-crash/17148365#17148365" rel="noreferrer noopener nofollow">answer I wrote over here</a>了解详情。</p></p>
<p style="font-size: 20px;">关于ios - observeValueForKeyPath 没有被调用,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/18189035/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/18189035/
</a>
</p>
页:
[1]