【问题标题】:Crashing in observeValueForKeyPath which attached to NSOperationQueue operationsCount在附加到 NSOperationQueue operationsCount 的 observeValueForKeyPath 中崩溃
【发布时间】:2012-06-26 15:00:45
【问题描述】:

我的 UIView 子类中有UITextView logView(尝试了atomicnonatomic)和NSOperationQueue uploadQueue 属性。 我在 NSOperationQueue 属性的 operationsCount 上添加了 KVO,如下所示:

[[self uploadQueue] addObserver:self
            forKeyPath:@"operationCount" 
               options:(NSKeyValueObservingOptionNew |
                        NSKeyValueObservingOptionOld)
               context:NULL];

观察者函数如下所示:

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([object isKindOfClass: [NSOperationQueue class]]) {
        NSLog(@"Keypath is: %@ change dictionary is: %@", keyPath, change);
        NSInteger testnew = [[change objectForKey: @"new"] integerValue];
        NSInteger testold = [[change objectForKey: @"old"] integerValue];
        if (testnew > testold) {
            [[self logView] setText: [NSString stringWithFormat: @"Uploading %d files", testnew]];
            objc_setAssociatedObject([self logView], @"max_value_of_uploads", [change objectForKey: @"new"], OBJC_ASSOCIATION_COPY);
        } else {
            NSInteger value = [objc_getAssociatedObject([self logView], @"max_value_of_uploads") integerValue]; 
            [[self logView] setText: [NSString stringWithFormat: @"Uploaded %d of %d files", testnew, value]];
        }
    }
}

uploadQueue 填充是这样的:

   ...
   NSDictionary *iter;
        NSEnumerator *enumerator = [objects objectEnumerator];
        while (iter = [enumerator nextObject]) {
            Uploader *op = [[Uploader alloc] initWithFileName: [iter objectForKey: @"fileName"] 
                                                             FileID: [[iter objectForKey: @"fileID"] integerValue] 
                                                       AndSessionID: [self sess]];
            //Uploader *op = [[Uploader alloc] init];
            [[self uploadQueue] addOperation: op];
   ...

没有if-else 块,一切正常:我收到了有关队列中操作数的 NSLog 消息,数字没问题等等。 但是使用 if-else 块,我会崩溃,看起来像这样:

bool _WebTryThreadLock(bool), 0x10617fb0: Tried to obtain the web lock from a thread other than the main thread or the web thread. This may be a result of calling to UIKit from a secondary thread. Crashing now...
1   WebThreadLock
2   -[UITextView setText:]
3   -[SincViewController observeValueForKeyPath:ofObject:change:context:]
4   NSKeyValueNotifyObserver
5   NSKeyValueDidChange
6   -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:]
7   -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:usingBlock:]
8   ____NSOQDelayedFinishOperations_block_invoke_0
9   -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:key:key:usingBlock:]
10  -[NSObject(NSKeyValueObservingPrivate) _changeValueForKey:usingBlock:]
11  __NSOQDelayedFinishOperations
12  _dispatch_after_timer_callback
13  _dispatch_source_invoke
14  _dispatch_queue_invoke
15  _dispatch_worker_thread2
16  _pthread_wqthread
17  start_wqthread

它在else 块中崩溃。 此外,我没有看到我的 logView 有任何变化。 感谢您未来的帮助和回复。

更新: performSelectorOnMainThread 设置文本时救了我。

【问题讨论】:

标签: objective-c ios multithreading key-value-observing nsoperationqueue


【解决方案1】:

更新 UI 时,请确保您处于主线程中。一个可能的解决方案如下:

dispatch_async(dispatch_get_main_queue(), ^{
    if (testnew > testold) {
        [[self logView] setText: [NSString stringWithFormat: @"Uploading %d files", testnew]];
        objc_setAssociatedObject([self logView], @"max_value_of_uploads", [change objectForKey: @"new"], OBJC_ASSOCIATION_COPY);
    } else {
        NSInteger value = [objc_getAssociatedObject([self logView], @"max_value_of_uploads") integerValue]; 
        [[self logView] setText: [NSString stringWithFormat: @"Uploaded %d of %d files", testnew, value]];
    }
}); 

请注意,使用dispatch_asyncdispatch_sync 取决于您所需的实现,但在后一种情况下,除非您检查您所在的线程,否则您可能会出现死锁。

另见:NSOperation, observer and thread error 有人建议将您的 UI 代码移至单独的方法:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  [self performSelectorOnMainThread:@selector(dataLoadingFinished:) withObject:nil waitUntilDone:YES];
}

..这是一条很好的替代路线。

【讨论】:

    【解决方案2】:

    我建议你在这里使用委托模式。您似乎将非常先进的技术与一些松散的代码混合在一起,这很快就会导致问题。例如,我认为您不需要关联对象。

    您的错误发生是因为您顺便从后台线程访问 UI。您应该将 UI 调用 (setText:) 包装在 performSelectorOnMainThread:withObject:waitUntilDone: 或块中。

    【讨论】:

    • 那是写错的,是的。但我并没有真正在主线程以外的任何线程中使用观察者函数。我认为问题在于KVO内部机制,也许它使用了额外的线程?无论如何,performSelectorOnMainThread 设置文本时救了我。
    • 观察者将在发生变化的任何线程中被调用。而且您使用的是 NSOperationQueue,所以是的,它将在后台。
    • 但我无法得到它。 NSOperation 实例从队列中消失后发生的更改。 NSOperationQueue 就会发生这种情况,它“存在”在主线程中。我的意思是,导致事件显然发生在所谓的后台线程中,但它自身的更改必须发生在主线程中。我哪里错了?谢谢。
    • 阅读链接的答案。苹果甚至告诉你不要这样做。
    • 我读过。但除了只是相信我想了解他们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    相关资源
    最近更新 更多