2015-04-01 87 views

回答

0

你可以定期檢查operations屬性,看看它是否改變了以前的引用(也許用一種運行的方法?)。如果確實如此,則檢查是否添加了操作。

這樣你就不需要子類NSOperationQueue或覆蓋addOperation

0

operationsNSOperationQueue的屬性是KVO兼容的。這意味着您可以通過addObserverForKeyPathobserveValueForKeyPath方法觀察此屬性的內容何時更改。請看下面的代碼片段:

@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上鍵 - 值觀察

相關問題