将操作添加到队列时,NSOperationQueue(代理/回调/通知)
问题描述:
有没有办法知道何时将某个操作添加到NSOperationQueue
实例? PS:目前,我不想对NSOperationQueue
进行子类化并覆盖所需的addOperation
API。将操作添加到队列时,NSOperationQueue(代理/回调/通知)
答
你可以定期检查operations
属性,看看它是否改变了以前的引用(也许用一种运行的方法?)。如果确实如此,则检查是否添加了操作。
这样你就不需要子类NSOperationQueue
或覆盖addOperation
。
答
operations
NSOperationQueue
的属性是KVO兼容的。这意味着您可以通过addObserverForKeyPath
和observeValueForKeyPath
方法观察此属性的内容何时更改。请看下面的代码片段:
@interface BigBrother : NSObject
//Just a demo method for filling queue with something
- (void) addSomeOperationsAndWaitTillFinished;
@end
@implementation BigBrother
- (void) observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSString *,id> *)change
context:(void *)context
{
//Triggers each time 'operations' property is changed
//(ex. operation is added or finished in this case)
//object is your NSOperationQueue
NSLog(@"Key path:%@\nObject:%@\nChange%@", keyPath, object, change);
}
- (void) addSomeOperationsAndWaitTillFinished
{
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
//Tell the queue we want to know when something happens to 'operations' property
[queue addObserver:self
forKeyPath:@"operations"
options:NSKeyValueObservingOptionNew
context:nil];
for (NSUInteger opNum = 0; opNum < 5; opNum++)
{
[queue addOperationWithBlock:^{sleep(1);}];
}
[queue waitUntilAllOperationsAreFinished];
}
你可以看到它是如何工作的,加入这一行到某处:
[[[BigBrother alloc] init] addSomeOperationsAndWaitTillFinished];
Apple's documentation上键 - 值观察