有没有办法知道何时将特定操作添加到NSOperationQueue
实例?
PS:目前,我对子类化NSOperationQueue
并覆盖所需的addOperation
API不感兴趣。
答案 0 :(得分:0)
您可以定期检查operations
属性,看看它是否随之前的引用而更改(也许是使用一直运行的方法?)。如果是,则检查是否添加了操作。
这样您就不需要继承NSOperationQueue
或覆盖addOperation
。
答案 1 :(得分:0)
operations
的{{1}}属性符合KVO标准。这意味着您可以使用NSOperationQueue
和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];
}
关于键值观察的