我在我的 UIView 子类中有UITextView logView
(尝试了atomic
和nonatomic
)和属性。NSOperationQueue uploadQueue
我在我NSOperationQueue
的财产上添加了 KVO,operationsCount
如下所示:
[[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
设置文本时救了我。