2013-02-16 53 views
0

只是試圖用NSOperationQueue做一個簡單的例子& NSInvocationOperation。這裏是我的代碼:爲什麼這些NSInvocationOperation不會實際運行?

- (void) runMethodsViaOperationQueue { 
    NSOperationQueue *thisQueue = [[NSOperationQueue alloc] init]; 
    NSInvocationOperation *logMethod1Invocation = [[NSInvocationOperation alloc] 
                initWithTarget:self 
                selector:@selector(logMethod1) 
                object:nil]; 
    [thisQueue addOperation:logMethod1Invocation]; 
} 

logMethod1僅僅是一個循環的NSLog語句,如:

- (void) logMethod1 { 
    for (int a = 0; a < 10; a++) { 
     NSLog(@"%s --> logMethod1: %i", __FUNCTION__, a); 
     if (a == 9) { 
      NSLog(@"%s --> ==================", __FUNCTION__); 
     } 
    } 
} 

類在主實例,其中runMethodsViaOperationQueue被調用。

MyOperationTestingClass *instantiateIt = [[MyOperationTestingClass alloc] init]; 
[instantiateIt runMethodsViaOperationQueue]; 

的是,當runMethodsViaOperationQueue執行沒有輸出,我想通過NSLog的期望。任何人都可以幫我澄清爲什麼這不起作用嗎?

回答

0

我真的試圖推斷多個NSInvocationOperation,所以創建NSInvocationOperations的數組:

NSArray *iOps = [NSArray arrayWithObjects:logMethod1Invocation, logMethod2Invocation, nil]; 

然後用這個數組addOperations:WaitUntilFinished:

[thisQueue addOperations:iOps waitUntilFinished:YES]; 

在執行時,輸出將顯示多個線程 -

2013-02-15 20:32:29.276 NSOperationTest[1060:1b03] -[MyOperationTestingClass logMethod1] --> logMethod1: 0 
2013-02-15 20:32:29.277 NSOperationTest[1060:1a03] -[MyOperationTestingClass logMethod2] --> logMethod2: 0 
2013-02-15 20:32:29.280 NSOperationTest[1060:1b03] -[MyOperationTestingClass logMethod1] --> logMethod1: 1 
2013-02-15 20:32:29.280 NSOperationTest[1060:1a03] -[MyOperationTestingClass logMethod2] --> logMethod2: 1 
相關問題